如果“隐藏归档”值更改,则“保存”按钮应为“已启用”。如果输入相同的值,则应再次禁用“保存”按钮

时间:2016-02-09 21:01:06

标签: jquery

我想根据表单元素的变化禁用/启用保存按钮。 但是当隐藏的输入字段值通过弹出按钮选择更改时,保存按钮不会受到影响。

以下是我的代码。 我正在尝试序列化旧的表单值并与更改的表单值进行比较。但我猜测隐藏的文件值不能序列化。

  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);

        }

以下代码适用于所有表单,除非有隐藏字段。 有人可以提出解决方案。

注意:通过按钮单击选择弹出窗口填充隐藏字段。##标题##

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:2)

问题似乎更多是关于尝试捕获程序化更改而不是更改隐藏字段。

作为answer here states.on('change'侦听器无法捕获程序化更改。当您更改其值时,您可以通过javascript在隐藏字段上“手动”触发更改事件。

我没有在您的问题中看到更新隐藏输入的javascript,但是手动调用更改事件的示例(应该适用于您)是:

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

相关问题