How do you handle a form change in jQuery?

后端 未结 13 2043
生来不讨喜
生来不讨喜 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:22

    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
    • for select it's defaultSelect
    • for checkbox/radio it's 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

提交回复
热议问题