如何处理jQuery中的表单更改?

时间:2022-12-06 22:50:10

In jQuery, is there a simple way to test if ANY of a form's elements have changed?

在jQuery中,是否有一种简单的方法来测试表单的元素是否发生了更改?

EDIT: I should have added that I only need to check on a click() event.

编辑:我应该加上,我只需要检查单击()事件。

EDIT: Sorry I really should have been more specific! Say I have a form and I have a button with the following:

编辑:对不起,我真的应该说得更具体些!假设我有一张表格,我有一个按钮,上面写着:

$('#mybutton').click(function() {
  // Here is where is need to test
  if(/* FORM has changed */) {
     // Do something
  }
});

How would I test if the form has changed since it was loaded?

如何测试表单自加载后是否发生了更改?

12 个解决方案

#1


116  

You can do this:

你可以这样做:

$("form :input").change(function() {
  $(this).closest('form').data('changed', true);
});
$('#mybutton').click(function() {
  if($(this).closest('form').data('changed')) {
     //do something
  }
});

This rigs a change event handler to inputs in the form, if any of them change it uses .data() to set a changed value to true, then we just check for that value on the click, this assumes that #mybutton is inside the form (if not just replace $(this).closest('form') with $('#myForm')), but you could make it even more generic, like this:

这个钻井平台改变事件处理程序的输入形式,如果其中任何一个改变它使用. data()来设置改变值为true,那么我们就检查这个值点击,这假设#色是在形式(如果不是取代美元(这).closest(形式)美元(“# myForm”)),但你可以让它更通用的,像这样:

$('.checkChangedbutton').click(function() {
  if($(this).closest('form').data('changed')) {
     //do something
  }
});

References: Updated

引用:更新

According to jQuery this is a filter to select all form controls.

根据jQuery,这是一个用于选择所有表单控件的过滤器。

http://api.jquery.com/input-selector/

http://api.jquery.com/input-selector/

The :input selector basically selects all form controls.

输入选择器主要选择所有的表单控件。

#2


42  

If you want to check if the form data, as it is going to be sent to the server, have changed, you can serialize the form data on page load and compare it to the current form data:

如果您想要检查表单数据是否已经更改(因为它将被发送到服务器),您可以将页面加载的表单数据序列化,并将其与当前的表单数据进行比较:

$(function() {

    var form_original_data = $("#myform").serialize(); 

    $("#mybutton").click(function() {
        if ($("#myform").serialize() != form_original_data) {
            // Something changed
        }
    });

});

#3


13  

A real time and simple solution:

一个实时而简单的解决方案:

$('form').on('keyup change paste', 'input, select, textarea', function(){
    console.log('Form changed!');
});

#4


10  

You can use multiple selectors to attach a callback to the change event for any form element.

可以使用多个选择器将回调附加到任何表单元素的change事件。

$("input, select").change(function(){
    // Something changed
});

EDIT

编辑

Since you mentioned you only need this for a click, you can simply modify my original code to this:

既然你提到你只需要点击一下,你可以简单的修改我的原始代码到这个:

$("input, select").click(function(){
    // A form element was clicked
});

EDIT #2

编辑# 2

Ok, you can set a global that is set once something has been changed like this:

好的,你可以设置一个全局变量一旦发生了这样的变化

var FORM_HAS_CHANGED = false;

$('#mybutton').click(function() {
    if (FORM_HAS_CHANGED) {
        // The form has changed
    }
});

$("input, select").change(function(){
    FORM_HAS_CHANGED = true;
});

#5


3  

Looking at the updated question try something like

看看更新后的问题,试试这样的方法

$('input, textarea, select').each(function(){
    $(this).data("val", $(this).val());
});
$('#button').click(function() {
    $('input, textarea, select').each(function(){
        if($(this).data("val")!==$(this).val()) alert("Things Changed");
    });
});

For the original question use something like

对于最初的问题,使用类似的东西

$('input').change(function() {
    alert("Things have changed!");
});

#6


2  

$('form :input').change(function() {
    // Something has changed
});

#7


2  

Here is an elegant solution.

这是一个优雅的解决方案。

There is hidden property for each input element on the form that you can use to determine whether or not the value was changed. Each type of input has it's own property name. For example

表单上的每个输入元素都有一个隐藏属性,您可以使用它来确定值是否被更改。每种类型的输入都有自己的属性名。例如

  • for text/textarea it's defaultValue
  • 用于文本/ textarea defaultValue
  • for select it's defaultSelect
  • 选择它的defaultSelect
  • for checkbox/radio it's defaultChecked
  • 复选框/无线电defaultChecked

Here is the example.

这是例子。

function bindFormChange($form) {

  function touchButtons() {
    var
      changed_objects = [],
      $observable_buttons = $form.find('input[type="submit"], button[type="submit"], button[data-object="reset-form"]');

    changed_objects = $('input:text, input:checkbox, input:radio, textarea, select', $form).map(function () {
      var
        $input = $(this),
        changed = false;

      if ($input.is('input:text') || $input.is('textarea') ) {
        changed = (($input).prop('defaultValue') != $input.val());
      }
      if (!changed && $input.is('select') ) {
        changed = !$('option:selected', $input).prop('defaultSelected');
      }
      if (!changed && $input.is('input:checkbox') || $input.is('input:radio') ) {
        changed = (($input).prop('defaultChecked') != $input.is(':checked'));
      }
      if (changed) {
        return $input.attr('id');
      }

    }).toArray();

    if (changed_objects.length) {
      $observable_buttons.removeAttr('disabled')   
    } else {
      $observable_buttons.attr('disabled', 'disabled');
    }
  };
  touchButtons();

  $('input, textarea, select', $form).each(function () {
    var $input = $(this);

    $input.on('keyup change', function () {
      touchButtons();
    });
  });

};

Now just loop thru the forms on the page and you should see submit buttons disabled by default and they will be activated ONLY if you indeed will change some input value on the form.

现在,只要在页面上的表单上循环,你就会看到提交按钮被默认禁用,只有当你确实改变了表单上的一些输入值时,它们才会被激活。

$('form').each(function () {
    bindFormChange($(this));
});

Implementation as a jQuery plugin is here https://github.com/kulbida/jmodifiable

jQuery插件的实现如下:https://github.com/kulbida/jmodiatable

#8


2  

var formStr = JSON.stringify($("#form").serializeArray());
...
function Submit(){
   var newformStr = JSON.stringify($("#form").serializeArray());
   if (formStr != newformStr){
      ...
         formChangedfunct();
      ...
   }
   else {
      ...
         formUnchangedfunct();
      ...
   }
}

#9


1  

You need jQuery Form Observe plugin. That's what you are looking for.

您需要jQuery表单观察插件。这就是你要找的。

#10


1  

Extending Udi's answer, this only checks on form submission, not on every input change.

扩展Udi的答案,这只检查表单提交,而不是每次输入更改。

$(document).ready( function () {
  var form_data = $('#myform').serialize();
  $('#myform').submit(function () {
      if ( form_data == $(this).serialize() ) {
        alert('no change');
      } else {
        alert('change');
      }
   });
});

#11


0  

First, I'd add a hidden input to your form to track the state of the form. Then, I'd use this jQuery snippet to set the value of the hidden input when something on the form changes:

首先,我将向窗体添加一个隐藏的输入,以跟踪窗体的状态。然后,当表单上的内容发生变化时,我将使用这个jQuery代码片段设置隐藏输入的值:

    $("form")
    .find("input")
    .change(function(){
        if ($("#hdnFormChanged").val() == "no")
        {
            $("#hdnFormChanged").val("yes");
        }
    });

When your button is clicked, you can check the state of your hidden input:

当您的按钮被单击时,您可以检查隐藏输入的状态:

$("#Button").click(function(){
    if($("#hdnFormChanged").val() == "yes")
    {
        // handler code here...
    }
});

#12


0  

$('form[name="your_form_name"] input, form[name="your_form_name"] select').click(function() {
  $("#result").html($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Form "your_form_name"</h2>
<form name="your_form_name">
  <input type="text" name="one_a" id="one_a" value="AAAAAAAA" />
  <input type="text" name="one_b" id="one_b" value="BBBBBBBB" />
  <input type="text" name="one_c" id="one_c" value="CCCCCCCC" />
  <select name="one_d">
    <option value="111111">111111</option>
    <option value="222222">222222</option>
    <option value="333333">333333</option>
  </select>
</form>
<hr/>
<h2>Form "your_other_form_name"</h2>
<form name="your_other_form_name">
  <input type="text" name="two_a" id="two_a" value="DDDDDDDD" />
  <input type="text" name="two_b" id="two_b" value="EEEEEEEE" />
  <input type="text" name="two_c" id="two_c" value="FFFFFFFF" />
  <input type="text" name="two_d" id="two_d" value="GGGGGGGG" />
  <input type="text" name="two_e" id="two_f" value="HHHHHHHH" />
  <input type="text" name="two_f" id="two_e" value="IIIIIIII" />
  <select name="two_g">
    <option value="444444">444444</option>
    <option value="555555">555555</option>
    <option value="666666">666666</option>
  </select>
</form>
<h2>Result</h2>
<div id="result">
  <h2>Click on a field..</h2>
</div>

In addition to above @JoeD's answer.

除了以上@JoeD的答案。

If you want to target fields in a particular form (assuming there are more than one forms) than just fields, you can use the following code:

如果您希望将字段定位为特定的表单(假设有多个表单),而不仅仅是字段,您可以使用以下代码:

$('form[name="your_form_name"] input, form[name="your_form_name"] select').click(function() {
    // A form element was clicked
});

#1


116  

You can do this:

你可以这样做:

$("form :input").change(function() {
  $(this).closest('form').data('changed', true);
});
$('#mybutton').click(function() {
  if($(this).closest('form').data('changed')) {
     //do something
  }
});

This rigs a change event handler to inputs in the form, if any of them change it uses .data() to set a changed value to true, then we just check for that value on the click, this assumes that #mybutton is inside the form (if not just replace $(this).closest('form') with $('#myForm')), but you could make it even more generic, like this:

这个钻井平台改变事件处理程序的输入形式,如果其中任何一个改变它使用. data()来设置改变值为true,那么我们就检查这个值点击,这假设#色是在形式(如果不是取代美元(这).closest(形式)美元(“# myForm”)),但你可以让它更通用的,像这样:

$('.checkChangedbutton').click(function() {
  if($(this).closest('form').data('changed')) {
     //do something
  }
});

References: Updated

引用:更新

According to jQuery this is a filter to select all form controls.

根据jQuery,这是一个用于选择所有表单控件的过滤器。

http://api.jquery.com/input-selector/

http://api.jquery.com/input-selector/

The :input selector basically selects all form controls.

输入选择器主要选择所有的表单控件。

#2


42  

If you want to check if the form data, as it is going to be sent to the server, have changed, you can serialize the form data on page load and compare it to the current form data:

如果您想要检查表单数据是否已经更改(因为它将被发送到服务器),您可以将页面加载的表单数据序列化,并将其与当前的表单数据进行比较:

$(function() {

    var form_original_data = $("#myform").serialize(); 

    $("#mybutton").click(function() {
        if ($("#myform").serialize() != form_original_data) {
            // Something changed
        }
    });

});

#3


13  

A real time and simple solution:

一个实时而简单的解决方案:

$('form').on('keyup change paste', 'input, select, textarea', function(){
    console.log('Form changed!');
});

#4


10  

You can use multiple selectors to attach a callback to the change event for any form element.

可以使用多个选择器将回调附加到任何表单元素的change事件。

$("input, select").change(function(){
    // Something changed
});

EDIT

编辑

Since you mentioned you only need this for a click, you can simply modify my original code to this:

既然你提到你只需要点击一下,你可以简单的修改我的原始代码到这个:

$("input, select").click(function(){
    // A form element was clicked
});

EDIT #2

编辑# 2

Ok, you can set a global that is set once something has been changed like this:

好的,你可以设置一个全局变量一旦发生了这样的变化

var FORM_HAS_CHANGED = false;

$('#mybutton').click(function() {
    if (FORM_HAS_CHANGED) {
        // The form has changed
    }
});

$("input, select").change(function(){
    FORM_HAS_CHANGED = true;
});

#5


3  

Looking at the updated question try something like

看看更新后的问题,试试这样的方法

$('input, textarea, select').each(function(){
    $(this).data("val", $(this).val());
});
$('#button').click(function() {
    $('input, textarea, select').each(function(){
        if($(this).data("val")!==$(this).val()) alert("Things Changed");
    });
});

For the original question use something like

对于最初的问题,使用类似的东西

$('input').change(function() {
    alert("Things have changed!");
});

#6


2  

$('form :input').change(function() {
    // Something has changed
});

#7


2  

Here is an elegant solution.

这是一个优雅的解决方案。

There is hidden property for each input element on the form that you can use to determine whether or not the value was changed. Each type of input has it's own property name. For example

表单上的每个输入元素都有一个隐藏属性,您可以使用它来确定值是否被更改。每种类型的输入都有自己的属性名。例如

  • for text/textarea it's defaultValue
  • 用于文本/ textarea defaultValue
  • for select it's defaultSelect
  • 选择它的defaultSelect
  • for checkbox/radio it's defaultChecked
  • 复选框/无线电defaultChecked

Here is the example.

这是例子。

function bindFormChange($form) {

  function touchButtons() {
    var
      changed_objects = [],
      $observable_buttons = $form.find('input[type="submit"], button[type="submit"], button[data-object="reset-form"]');

    changed_objects = $('input:text, input:checkbox, input:radio, textarea, select', $form).map(function () {
      var
        $input = $(this),
        changed = false;

      if ($input.is('input:text') || $input.is('textarea') ) {
        changed = (($input).prop('defaultValue') != $input.val());
      }
      if (!changed && $input.is('select') ) {
        changed = !$('option:selected', $input).prop('defaultSelected');
      }
      if (!changed && $input.is('input:checkbox') || $input.is('input:radio') ) {
        changed = (($input).prop('defaultChecked') != $input.is(':checked'));
      }
      if (changed) {
        return $input.attr('id');
      }

    }).toArray();

    if (changed_objects.length) {
      $observable_buttons.removeAttr('disabled')   
    } else {
      $observable_buttons.attr('disabled', 'disabled');
    }
  };
  touchButtons();

  $('input, textarea, select', $form).each(function () {
    var $input = $(this);

    $input.on('keyup change', function () {
      touchButtons();
    });
  });

};

Now just loop thru the forms on the page and you should see submit buttons disabled by default and they will be activated ONLY if you indeed will change some input value on the form.

现在,只要在页面上的表单上循环,你就会看到提交按钮被默认禁用,只有当你确实改变了表单上的一些输入值时,它们才会被激活。

$('form').each(function () {
    bindFormChange($(this));
});

Implementation as a jQuery plugin is here https://github.com/kulbida/jmodifiable

jQuery插件的实现如下:https://github.com/kulbida/jmodiatable

#8


2  

var formStr = JSON.stringify($("#form").serializeArray());
...
function Submit(){
   var newformStr = JSON.stringify($("#form").serializeArray());
   if (formStr != newformStr){
      ...
         formChangedfunct();
      ...
   }
   else {
      ...
         formUnchangedfunct();
      ...
   }
}

#9


1  

You need jQuery Form Observe plugin. That's what you are looking for.

您需要jQuery表单观察插件。这就是你要找的。

#10


1  

Extending Udi's answer, this only checks on form submission, not on every input change.

扩展Udi的答案,这只检查表单提交,而不是每次输入更改。

$(document).ready( function () {
  var form_data = $('#myform').serialize();
  $('#myform').submit(function () {
      if ( form_data == $(this).serialize() ) {
        alert('no change');
      } else {
        alert('change');
      }
   });
});

#11


0  

First, I'd add a hidden input to your form to track the state of the form. Then, I'd use this jQuery snippet to set the value of the hidden input when something on the form changes:

首先,我将向窗体添加一个隐藏的输入,以跟踪窗体的状态。然后,当表单上的内容发生变化时,我将使用这个jQuery代码片段设置隐藏输入的值:

    $("form")
    .find("input")
    .change(function(){
        if ($("#hdnFormChanged").val() == "no")
        {
            $("#hdnFormChanged").val("yes");
        }
    });

When your button is clicked, you can check the state of your hidden input:

当您的按钮被单击时,您可以检查隐藏输入的状态:

$("#Button").click(function(){
    if($("#hdnFormChanged").val() == "yes")
    {
        // handler code here...
    }
});

#12


0  

$('form[name="your_form_name"] input, form[name="your_form_name"] select').click(function() {
  $("#result").html($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Form "your_form_name"</h2>
<form name="your_form_name">
  <input type="text" name="one_a" id="one_a" value="AAAAAAAA" />
  <input type="text" name="one_b" id="one_b" value="BBBBBBBB" />
  <input type="text" name="one_c" id="one_c" value="CCCCCCCC" />
  <select name="one_d">
    <option value="111111">111111</option>
    <option value="222222">222222</option>
    <option value="333333">333333</option>
  </select>
</form>
<hr/>
<h2>Form "your_other_form_name"</h2>
<form name="your_other_form_name">
  <input type="text" name="two_a" id="two_a" value="DDDDDDDD" />
  <input type="text" name="two_b" id="two_b" value="EEEEEEEE" />
  <input type="text" name="two_c" id="two_c" value="FFFFFFFF" />
  <input type="text" name="two_d" id="two_d" value="GGGGGGGG" />
  <input type="text" name="two_e" id="two_f" value="HHHHHHHH" />
  <input type="text" name="two_f" id="two_e" value="IIIIIIII" />
  <select name="two_g">
    <option value="444444">444444</option>
    <option value="555555">555555</option>
    <option value="666666">666666</option>
  </select>
</form>
<h2>Result</h2>
<div id="result">
  <h2>Click on a field..</h2>
</div>

In addition to above @JoeD's answer.

除了以上@JoeD的答案。

If you want to target fields in a particular form (assuming there are more than one forms) than just fields, you can use the following code:

如果您希望将字段定位为特定的表单(假设有多个表单),而不仅仅是字段,您可以使用以下代码:

$('form[name="your_form_name"] input, form[name="your_form_name"] select').click(function() {
    // A form element was clicked
});