Bruce Xu
Bruce Xu

Reputation: 353

jQuery - Detect value change which use .val() function

We all know that use the val() will not trigger the change event, so we also use .trigger('change') behind the val().

But the problem is that someone write the val() did't with trigger() and it's a external file that I can't edit it.

So, how can I detect value change through some code same like below:

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

Upvotes: 7

Views: 3930

Answers (5)

Andrei Gogu
Andrei Gogu

Reputation: 11

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

Upvotes: 1

Josh Whitlow
Josh Whitlow

Reputation: 481

I commonly use the solution from this post to get around problems like this one:

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

Upvotes: 0

Jedi
Jedi

Reputation: 87

Try:

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

Thank you,

Upvotes: 0

BMH
BMH

Reputation: 4340

My suggestion is to override jquery's val()

var originalValFn = jQuery.fn.val;

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

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

Upvotes: 1

Jedi
Jedi

Reputation: 87

Try:

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

or

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

Thank you,

Upvotes: -1

Related Questions