Detecting data changes in forms using jQuery

后端 未结 10 2035
遇见更好的自我
遇见更好的自我 2020-12-05 13:27

I\'m using ASP.NET 2.0 with a Master Page, and I was wondering if anyone knew of a way to detect when the fields within a certain

or fieldset<
10条回答
  •  生来不讨喜
    2020-12-05 14:14

    Quick (but very dirty) solution

    This is quick, but it won't take care of ctrl+z or cmd+z and it will give you a false positive when pressing shift, ctrl or the tab key:

    $('#my-form').on('change keyup paste', ':input', function(e) {
        // The form has been changed. Your code here.
    });
    

    Test it with this fiddle.


    Quick (less dirty) solution

    This will prevent false positives for shift, ctrl or the tab key, but it won't handle ctrl+z or cmd+z:

    $('#my-form').on('change keyup paste', ':input', function(e) {
    
      var keycode = e.which;
    
      if (e.type === 'paste' || e.type === 'change' || (
          (keycode === 46 || keycode === 8) || // delete & backspace
          (keycode > 47 && keycode < 58) || // number keys
          keycode == 32 || keycode == 13 || // spacebar & return key(s) (if you want to allow carriage returns)
          (keycode > 64 && keycode < 91) || // letter keys
          (keycode > 95 && keycode < 112) || // numpad keys
          (keycode > 185 && keycode < 193) || // ;=,-./` (in order)
          (keycode > 218 && keycode < 223))) { // [\]' (in order))
    
        // The form has been changed. Your code here.
    
      }
    
    });
    

    Test it with this fiddle.


    A complete solution

    If you want to handle all the cases, you should use:

    // init the form when the document is ready or when the form is populated after an ajax call
    $(document).ready(function() {
      $('#my-form').find(':input').each(function(index, value) {
        $(this).data('val', $(this).val());
      });
    })
    
    $('#my-form').on('change paste', ':input', function(e) {
      $(this).data('val', $(this).val());
      // The form has been changed. Your code here.
    });
    
    $('#my-form').on('keyup', ':input', function(e) {
      if ($(this).val() != $(this).data('val')) {
        $(this).data('val', $(this).val());
        // The form has been changed. Your code here. 
      }
    });
    

    Test it with this fiddle.

提交回复
热议问题