If the Hidden Filed values ​​change, the Save button must be enabled. If the same value is entered, the "Save" button should be disabled again

I am trying to disable / enable the save button based on changing form elements. But when the values ​​of the hidden input field change when the button is pressed, the save button does not change.

Below is my code. I am trying to serialize old form values ​​and compare with changed form values. But hidden registered values ​​cannot be serialized, I think.

  function toggleSave() {
           $('form')
            .each(function () {
                $(this).data('serialized', $(this).serialize())
            })
            .on('change input', function () {
                $(this)
                     .find('button.Save')
                        .prop('disabled', $(this).serialize() == $(this).data('serialized'))
                ;
            })
            .find('button.Save')
               .prop('disabled', true);

        }

The code below works great for all forms except when there are hidden fields. Can someone suggest a solution.

Note. Hidden fields are filled in using the "Select pop-up window" button. ## Title ##

+4
2

, , , .

, .on('change'. "" javascript .

javascript , , ( ):

$('input:hidden').val('a new value').change();

+2

. , . , , , .

var inputHiddenFields = 0;
$(function () {
  // count the number of hidden input fields
  inputHiddenFields = $('form :hidden').length;
  $('form').find('button.Save').prop('disabled', true);

  // set each hidden input data attribute isChanged to false
  $('form :hidden').each(function(index, ele) {
    $(this).data('isChanged', false);
  });

  $('form :hidden').on('input', function (e) {
    // set data attribute isChanged to true
    $(this).data('isChanged', true);

    // count the number of hidden input fields with data attribute isChanged set to  true
    var changedInputHiddenFields = $('form :hidden').filter(function(index, ele) {
      return $(this).data('isChanged');
    }).length;

    // compare the number of all hidden input fields with changed one
    $(this).parent().find('button.Save').prop('disabled', inputHiddenFields != changedInputHiddenFields);
  });

  $('#clickme').on('click', function(e) {
    $('#input2').val('test');
  });

  $('#clickmeandtrigger').on('click', function(e) {
    $('#input2').val('test').trigger('input');
  });
});
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>


<form action="z.html">
    <input type="text" id="input1" name="input1">
    <input type="hidden"  id="input2" name="input1">
    <button class="Save">Save</button>
</form>
<button id="clickme">Click Me</button>
<button id="clickmeandtrigger">Click Me And Trigger</button>
+2

Source: https://habr.com/ru/post/1628030/


All Articles