[jquery] jQuery-숨겨진 입력 필드에서 값 변경 감지

AJAX 응답을 통해 값이 업데이트되는 숨겨진 텍스트 필드가 있습니다.

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

이 값이 변경되면 AJAX 요청을 시작하고 싶습니다. 누구든지 변경을 감지하는 방법에 대해 조언 할 수 있습니까?

다음 코드가 있지만 값을 찾는 방법을 모릅니다.

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



답변

그래서 이것은 늦었지만이 스레드를 우연히 본 사람에게 유용 할 경우를 대비하여 답을 찾았습니다.

숨겨진 요소의 값을 변경해도 .change () 이벤트가 자동으로 발생하지 않습니다. 따라서 해당 값을 설정하는 위치에 관계없이 jQuery에 값을 트리거하도록 지시해야합니다.

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

그런 경우

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

예상대로 작동합니다.


답변

숨겨진 입력은 변경시 “change”이벤트를 트리거하지 않기 때문에 대신 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] );


답변

아래 함수를 사용하면됩니다. type 요소를 변경할 수도 있습니다.

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

숨겨진 요소의 값을 변경해도 .change () 이벤트가 자동으로 발생하지 않습니다. 따라서 해당 값을 설정하는 위치에 관계없이 jQuery에 값을 트리거하도록 지시해야합니다.

HTML

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

자바 스크립트

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/


답변

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

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


답변

사용할 수 있습니다 Object.defineProperty()입력 요소의 ‘값’속성을 재정의하고 변화하는 동안 무엇을하기 위해.

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/


답변

이 예에서는 숨겨진 초안 필드의 값이 변경 될 때마다 초안 필드 값을 반환합니다 (크롬 브라우저).

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

       }
  };
})();


답변

의 오프 구축 비크의 대답 , 여기 당신이 그 이후의 변경 이벤트 get 및 해고 보장하기 위해 주어진 숨겨진 입력 요소에 한 번 호출 할 수 있습니다 구현입니다 때마다 입력 요소의 값이 변경 :

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