복붙노트

[JQUERY] jQuery를이 - 숨겨진 입력 필드에 값 변경을 감지

JQUERY

jQuery를이 - 숨겨진 입력 필드에 값 변경을 감지

해결법


  1. 1.이 방법은 늦게,하지만 난이 스레드를 통해 제공이 누군가에게 도움이 될 경우에 대한 답을 발견했습니다 그래서.

    이 방법은 늦게,하지만 난이 스레드를 통해 제공이 누군가에게 도움이 될 경우에 대한 답을 발견했습니다 그래서.

    숨겨진 요소 값의 변화는 자동으로 .change () 이벤트가 발생하지 않습니다. 당신이 그 값을 설정하는 것이 어디 그래서, 당신은 또한 그것을 실행하는 데 jQuery를 이야기해야합니다.

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

    그런 경우가 있어요되면,

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

    예상대로 작동합니다.


  2. 2.숨겨진 입력이 변화의 "변화"이벤트를 트리거하지 않기 때문에, 내가 대신이 트리거 MutationObserver을 사용했다.

    숨겨진 입력이 변화의 "변화"이벤트를 트리거하지 않기 때문에, 내가 대신이 트리거 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] );
    

  3. 3.당신은 단순히 아래 기능을 사용할 수 있습니다, 당신은 또한 유형 요소를 변경할 수 있습니다.

    당신은 단순히 아래 기능을 사용할 수 있습니다, 당신은 또한 유형 요소를 변경할 수 있습니다.

     $("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/


  4. 4.

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

  5. 5.이 입력 요소의 '값'속성을 재정의하고 변화하는 동안 아무것도 위해 Object.defineProperty ()을 사용할 수있다.

    이 입력 요소의 '값'속성을 재정의하고 변화하는 동안 아무것도 위해 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/


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

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

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

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

    비크의 대답의 오프 구축, 여기에 당신이 그 이후의 변경 이벤트 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]);
    });
    

  8. 8.이 스레드가 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");
        });
    }
    
  9. from https://stackoverflow.com/questions/6533087/jquery-detect-value-change-on-hidden-input-field by cc-by-sa and MIT license