How do you handle a form change in jQuery?

后端 未结 13 2097
生来不讨喜
生来不讨喜 2020-11-28 21:18

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

EDIT: I should have added that I only need to check on a c

13条回答
  •  一个人的身影
    2020-11-28 21:38

    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:

    $('.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.

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

    The :input selector basically selects all form controls.

提交回复
热议问题