使用jQuery,如何找到表单是否已更改? [英] Using jQuery, how can I find if a form has changed?
问题描述
我想知道表单是否发生了变化。表单可以包含任何表单元素,例如input,select,textarea等。基本上我想要一种向用户显示他们对表单进行了未保存更改的方法。
I want to know if a form has changed at all. The form can contain any form element, such as input, select, textarea etc. Basically I want a way to display to the user that they have unsaved changed made to a form.
如何使用jQuery执行此操作?
How can I do this using jQuery?
澄清一下:我想抓住对表单的任何更改,不仅要输入元素,还要注意所有其他表单元素,textarea,select等。
推荐答案
我在这种情况下通常采用的方法是检查序列化的表单值。因此,您的想法是使用 $。fn.serialize $ c计算初始表单状态$ c>
方法。然后在需要时你只需将当前状态与原始序列化字符串进行比较。
The approach I usually take in such a case is that I check serialized form value. So the idea is that you calculate initial form state with $.fn.serialize
method. Then when needed you just compare current state with the original serialized string.
定位所有输入元素(select,textarea,checkbox,input-text等)表单你可以使用伪选择器:输入
。
To target all input elements (select, textarea, checkbox, input-text, etc.) within a form you can use pseudo selector :input
.
例如:
var $form = $('form'),
origForm = $form.serialize();
$('form :input').on('change input', function() {
$('.change-message').toggle($form.serialize() !== origForm);
});
.change-message {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="change-message">You have unsaved changes.</div>
<div>
<textarea name="description" cols="30" rows="3"></textarea>
</div>
<div>Username: <input type="text" name="username" /></div>
<div>
Type:
<select name="type">
<option value="1">Option 1</option>
<option value="2" selected>Option 2</option>
<option value="3">Option 3</option>
</select>
</div>
<div>
Status: <input type="checkbox" name="status" value="1" /> 1
<input type="checkbox" name="status" value="2" /> 2
</div>
</form>
这篇关于使用jQuery,如何找到表单是否已更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!