简体   繁体   中英

How to detect when the value of an input changes dynamically with JS / Jquery

I am able to detect if an input changes value while typing, pasting, etc, But if the value changed dynamically from another script I am unable to detect it:

Lets say I have an input

<input id="testInput" value="Type Here" />

And if the value changes by typing on it I want to alert "changed"

$('#testInput').on('input', function(){
    alert("changed");
});

This works, but if the value changed dynamically from another script, I can't trigger the alert:

$('#testInput').val("Dynamic Value"); //This doesn't show the alert

I want to be able to detect if the value changed at all, either by typing, pasting, or dynamically from a script or action.

.val() Is beeing executed in many different places, so changing .val() all over the code for something else like .val().trigger("change") is not an option.

Here is a jsfiddle with a better example:

https://jsfiddle.net/xpvt214o/486146/

An alternative is overriding the function $.fn.val()

This is a basic approach to start with.

 var $val = $.fn.val; $.fn.val = function(newVal) { if (this.attr('id') === 'target') this.trigger('input'); $val.call(this, newVal); } $('#target').on('input', function() { alert("changed"); }); $('#target').val('Ele from Stack'); $('#target2').val('Ele from Stack2'); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id='target' /> <input id='target2' /> 

只需触发事件!

$('#testInput').val("Dynamic Value").trigger("input");

Inpired of Ele 's answer...

While overriding the .val() function... Instead of comparing the id, you could add an agrument for the even to trigger! If it's not provided, there is no change from the "regular" .val() function. If provided, it triggers the event.

You will have to change every places where the value is programmatically changed anyway, but in a more practical way. ;)

 var $val = $.fn.val; $.fn.val = function(newVal,eventToTrigger) { if (eventToTrigger != null) this.trigger(eventToTrigger); $val.call(this, newVal); } $('.someClass').on('input', function() { alert("Programmatically inputted!"); }); $('.otherClass').on('change', function() { alert("Programmatically changed!"); }); $('.someClass').val('Hello you!','input'); $('.otherClass').val('Doing fine?','change'); $('#whatever').val('Hehehe.'); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" class="someClass"> <input type="text" class="otherClass"> <input type="text" id="whatever"> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM