jQuery - 检测隐藏输入字段上的值变化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6533087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:00:37  来源:igfitidea点击:

jQuery - Detect value change on hidden input field

jqueryevent-handlingfieldonchangehidden

提问by Ben

I have a hidden text field whose value gets updated via an AJAX response.

我有一个隐藏的文本字段,其值通过 AJAX 响应更新。

<input type="hidden" value="" name="userid" id="useid" />

When this value changes, I would like to fire an AJAX request. Can anyone advise on how to detect the change?

当这个值改变时,我想触发一个 AJAX 请求。任何人都可以就如何检测变化提出建议吗?

I have the following code, but do not know how to look for the value:

我有以下代码,但不知道如何查找值:

$('#userid').change( function() {  
    alert('Change!'); 
}) 

回答by yycroman

So this is way late, but I've discovered an answer, in case it becomes useful to anyone who comes across this thread.

所以这已经很晚了,但我发现了一个答案,以防它对遇到此线程的任何人有用。

Changes in value to hidden elements don't automatically fire the .change() event. So, wherever it is that you're setting that value, you also have to tell jQuery to trigger it.

隐藏元素的值更改不会自动触发 .change() 事件。因此,无论您在何处设置该值,都必须告诉 jQuery 触发它。

function setUserID(myValue) {
     $('#userid').val(myValue)
                 .trigger('change');
}

Once that's the case,

既然如此,

$('#userid').change(function(){
      //fire your ajax call  
})

should work as expected.

应该按预期工作。

回答by lulalala

Since hidden input does not trigger "change" event on change, I used MutationObserver to trigger this instead.

由于隐藏输入不会在更改时触发“更改”事件,因此我使用 MutationObserver 来触发它。

(Sometimes hidden input value changes are done by some other scripts you can't modify)

(有时隐藏的输入值更改是由您无法修改的其他一些脚本完成的)

This does not work in IE10 and below

这在 IE10 及以下版本中不起作用

MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

var trackChange = function(element) {
  var observer = new MutationObserver(function(mutations, observer) {
    if(mutations[0].attributeName == "value") {
        $(element).trigger("change");
    }
  });
  observer.observe(element, {
    attributes: true
  });
}

// Just pass an element to the function to start tracking
trackChange( $("input[name=foo]")[0] );

回答by Tarun Gupta

You can simply use the below function, You can also change the type element.

您可以简单地使用以下功能,您还可以更改类型元素。

 $("input[type=hidden]").bind("change", function() {
       alert($(this).val()); 
 });

Changes in value to hidden elements don't automatically fire the .change() event. So, wherever it is that you're setting that value, you also have to tell jQuery to trigger it.

隐藏元素的值更改不会自动触发 .change() 事件。因此,无论您在何处设置该值,都必须告诉 jQuery 触发它。

HTML

HTML

 <div id="message"></div>
<input type="hidden" id="testChange" value="0"  />    

JAVASCRIPT

爪哇脚本

var $message = $('#message');
var $testChange = $('#testChange');
var i = 1;

function updateChange() {
    $message.html($message.html() + '<p>Changed to ' + $testChange.val() + '</p>');
}

$testChange.on('change', updateChange);

setInterval(function() {
    $testChange.val(++i).trigger('change');; 
    console.log("value changed" +$testChange.val());
}, 3000);

updateChange();

should work as expected.

应该按预期工作。

http://jsfiddle.net/7CM6k/3/

http://jsfiddle.net/7CM6k/3/

回答by Digambar Patil

$('#userid').change(function(){
  //fire your ajax call  
});

$('#userid').val(10).change();

回答by Viktar Tserashchuk

It is possible to use Object.defineProperty()in order to redefine the 'value' property of the input element and do anything during its changing.

可以使用Object.defineProperty()以重新定义输入元素的“值”属性并在其更改期间执行任何操作。

Object.defineProperty()allows us to define a getter and setter for a property, thus controlling it.

Object.defineProperty()允许我们为属性定义 getter 和 setter,从而控制它。

replaceWithWrapper($("#hid1")[0], "value", function(obj, property, value) { 
  console.log("new value:", value)
});

function replaceWithWrapper(obj, property, callback) {
  Object.defineProperty(obj, property, new function() {
    var _value = obj[property];
    return {
      set: function(value) {
        _value = value;
        callback(obj, property, value)
      },
      get: function() {
        return _value;
      }
    }
  });
}

$("#hid1").val(4);

https://jsfiddle.net/bvvmhvfk/

https://jsfiddle.net/bvvmhvfk/

回答by user2677034

This example returns the draft field value every time the hidden draft field changes its value (chrome browser):

此示例在每次隐藏草稿字段更改其值时返回草稿字段值(chrome 浏览器):

var h = document.querySelectorAll('input[type="hidden"][name="draft"]')[0];
//or jquery.....
//var h = $('input[type="hidden"][name="draft"]')[0];

observeDOM(h, 'n', function(draftValue){ 
  console.log('dom changed draftValue:'+draftValue);
});


var observeDOM = (function(){
var MutationObserver = window.MutationObserver || 
window.WebKitMutationObserver;

  return function(obj, thistime, callback){
    if(typeof obj === 'undefined'){
      console.log('obj is undefined');
      return;
    }

    if( MutationObserver ){

        // define a new observer
        var obs = new MutationObserver(function(mutations, observer){

            if( mutations[0].addedNodes.length || mutations[0].removedNodes.length ){

               callback('pass other observations back...');

            }else if(mutations[0].attributeName == "value" ){

               // use callback to pass back value of hidden form field                            
               callback( obj.value );

            }

        });

        // have the observer observe obj for changes in children
        // note 'attributes:true' else we can't read the input attribute value
        obs.observe( obj, { childList:true, subtree:true, attributes:true  });

       }
  };
})();

回答by GuyPaddock

Building off of Viktar's answer, here's an implementation you can call once on a given hidden input element to ensure that subsequent change event get fired whenever the value of the input element changes:

基于Viktar 的回答,这里有一个实现,您可以在给定的隐藏输入元素上调用一次,以确保在输入元素的值发生更改时触发后续更改事件:

/**
 * Modifies the provided hidden input so value changes to trigger events.
 *
 * After this method is called, any changes to the 'value' property of the
 * specified input will trigger a 'change' event, just like would happen
 * if the input was a text field.
 *
 * As explained in the following SO post, hidden inputs don't normally
 * trigger on-change events because the 'blur' event is responsible for
 * triggering a change event, and hidden inputs aren't focusable by virtue
 * of being hidden elements:
 * https://stackoverflow.com/a/17695525/4342230
 *
 * @param {HTMLInputElement} inputElement
 *   The DOM element for the hidden input element.
 */
function setupHiddenInputChangeListener(inputElement) {
  const propertyName = 'value';

  const {get: originalGetter, set: originalSetter} =
    findPropertyDescriptor(inputElement, propertyName);

  // We wrap this in a function factory to bind the getter and setter values
  // so later callbacks refer to the correct object, in case we use this
  // method on more than one hidden input element.
  const newPropertyDescriptor = ((_originalGetter, _originalSetter) => {
    return {
      set: function(value) {
        const currentValue = originalGetter.call(inputElement);

        // Delegate the call to the original property setter
        _originalSetter.call(inputElement, value);

        // Only fire change if the value actually changed.
        if (currentValue !== value) {
          inputElement.dispatchEvent(new Event('change'));
        }
      },

      get: function() {
        // Delegate the call to the original property getter
        return _originalGetter.call(inputElement);
      }
    }
  })(originalGetter, originalSetter);

  Object.defineProperty(inputElement, propertyName, newPropertyDescriptor);
};

/**
 * Search the inheritance tree of an object for a property descriptor.
 *
 * The property descriptor defined nearest in the inheritance hierarchy to
 * the class of the given object is returned first.
 *
 * Credit for this approach:
 * https://stackoverflow.com/a/38802602/4342230
 *
 * @param {Object} object
 * @param {String} propertyName
 *   The name of the property for which a descriptor is desired.
 *
 * @returns {PropertyDescriptor, null}
 */
function findPropertyDescriptor(object, propertyName) {
  if (object === null) {
    return null;
  }

  if (object.hasOwnProperty(propertyName)) {
    return Object.getOwnPropertyDescriptor(object, propertyName);
  }
  else {
    const parentClass = Object.getPrototypeOf(object);

    return findPropertyDescriptor(parentClass, propertyName);
  }
}

Call this on document ready like so:

在文档就绪时调用它,如下所示:

$(document).ready(function() {
  setupHiddenInputChangeListener($('myinput')[0]);
});

回答by mdbxz

Although this thread is 3 years old, here is my solution:

虽然这个线程已经有 3 年历史了,但这是我的解决方案:

$(function ()
{
    keep_fields_uptodate();
});

function keep_fields_uptodate()
{
    // Keep all fields up to date!
    var $inputDate = $("input[type='date']");
    $inputDate.blur(function(event)
    {
        $("input").trigger("change");
    });
}