jQuery - 检测隐藏输入字段的值更改

时间:2011-06-30 10:00:59

标签: jquery event-handling field onchange hidden

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

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

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

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

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

8 个答案:

答案 0 :(得分:577)

所以这已经很晚了,但我发现了一个答案,以防它对遇到这个帖子的人有用。

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

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

一旦出现这种情况,

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

应该按预期工作。

答案 1 :(得分:22)

由于隐藏的输入不会触发&#34;更改&#34;更改事件时,我使用MutationObserver来触发它。

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

这在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] );

答案 2 :(得分:9)

您只需使用以下功能,您也可以更改类型元素。

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

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

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

应该按预期工作。

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

答案 3 :(得分:4)

可以使用Object.defineProperty()来重新定义输入元素的'value'属性,并在更改过程中执行任何操作。

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/

答案 4 :(得分:2)

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

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

答案 5 :(得分:0)

&lt; p&gt;每次隐藏的草稿字段更改其值(chrome浏览器)时,此示例都会返回草稿字段值:&lt; / p&gt; &lt; pre&gt;&lt; code&gt; var h = document.querySelectorAll('input [type =“hidden”] [name =“draft”]')[0]; //或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函数(obj,thistime,callback){     if(typeof obj ==='undefined'){       console.log('obj is undefined');       返回;     }     if(MutationObserver){         //定义一个新的观察者         var obs = new MutationObserver(function(mutation,observer){             if(mutation [0] .addedNodes.length || mutation [0] .removedNodes.length){                回调('传回其他观察......');             } else if(mutation [0] .attributeName ==“value”){                //使用回调传递隐藏表单字段的值                回调(obj.value);             }         });         //让观察者观察obj是否有儿童的变化         //注意'attributes:true'否则我们无法读取输入属性值         obs.observe(obj,{childList:true,subtree:true,attributes:true});        }   }; })(); &LT; /代码&GT;&LT; /预&GT;

答案 6 :(得分:0)

Viktar's answer为基础,这是一种实现,您可以在给定的隐藏输入元素上调用一次,以确保每当输入元素的值更改时都会触发后续的change事件:

/**
 * 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);
  }
}

在文档上随时调用它,就像这样:

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

答案 7 :(得分:-3)

虽然这个帖子已经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");
    });
}