JQuery - Define a value change using the .val () function

We all know that using val() will not result in a change event, so we also use .trigger('change') for val() .

But the problem is that someone writes val() did't with trigger() , and this is an external file that I cannot edit it.

So, how can I detect a change in value through some code, as shown below:

 $('.elem').on('change', function(){ // do something }); 
+5
source share
5 answers

My suggestion is to override jquery val()

 var originalValFn = jQuery.fn.val; jQuery.fn.val = function() { this.trigger('change'); originalValFn.apply( this, arguments ); } 

jsfiddle: http://jsfiddle.net/2L7hohjz/js

+1
source
 var originalValFn = jQuery.fn.val; function getErrorObject(){ try { throw Error('') } catch(err) { return err; } } jQuery.fn.val = function() { if ($(this).hasClass( "element" )) { var err = getErrorObject(); var caller_line = err.stack.split("\n")[4]; var index = caller_line.indexOf("at "); var clean = caller_line.slice(index+2, caller_line.length); console.log(clean); console.log(arguments); } originalValFn.apply( this, arguments ); }; 
+1
source

Try:

 setTimeout(function() { if (currentValue != previousValue) { // do something } }, 500); 

Thanks,

0
source

I usually use the solution from this post to get around issues like this:

hidden input change event

 watchField('.elem', function(){ //do some stuff here }); function watchField(selector, callback) { var input = $(selector); var oldvalue = input.val(); setInterval(function(){ if (input.val()!=oldvalue){ oldvalue = input.val(); callback(); } }, 100); } 
0
source

Try:

 $('.elem').on('keyUp', function(){ // do something }); 

or

 $('.elem').on('lostFocus', function(){ // do something }); 

Thanks,

-1
source

Source: https://habr.com/ru/post/1209046/


All Articles