Javascript 使用 jQuery,如何查找表单是否已更改?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26796634/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:23:26  来源:igfitidea点击:

Using jQuery, how can I find if a form has changed?

javascriptjquery

提问by Weblurk

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.

我想知道表格是否发生了变化。表单可以包含任何表单元素,例如输入、选择、文本区域等。基本上我想要一种方式向用户显示他们对表单所做的未保存更改。

How can I do this using jQuery?

我如何使用 jQuery 做到这一点?

To clarify: I want to catch ANY change to the form, not only to input elements but to all other form elements as well, textarea, select etc.

澄清:我想捕捉对表单的任何更改,不仅是输入元素,还包括所有其他表单元素,textarea、select 等。

回答by dfsq

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.serializemethod. Then when needed you just compare current state with the original serialized string.

在这种情况下,我通常采用的方法是检查序列化表单值。所以这个想法是你用$.fn.serialize方法计算初始表单状态。然后在需要时,您只需将当前状态与原始序列化字符串进行比较。

To target all input elements (select, textarea, checkbox, input-text, etc.) within a form you can use pseudo selector :input.

要定位表单中的所有输入元素(选择、文本区域、复选框、输入文本等),您可以使用伪选择器:input

For example:

例如:

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>