Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
});
like image 610
Harry Yu Avatar asked Dec 15 '14 04:12

Harry Yu


People also ask

What is the use of val () method in jQuery?

The val() method returns or sets the value attribute of the selected elements. When used to return value: This method returns the value of the value attribute of the FIRST matched element.

How can check value change or not in jQuery?

The change() is an inbuilt method in jQuery that is used to detect the change in value of input fields. This method works only on the “<input>, <textarea> and <select>” elements. Parameter: It accepts an optional parameter “function”. Return Value: It returns the element with the modification.

Does jQuery Val trigger change event?

When you dynamically set a value in a textfield using jQuery . val(), you have to manually trigger the . change event if you want to add extra code that trigger when the value of the field change.

What is the difference between Val and value in jQuery?

attr('value') returns the value that was before editing input field. And . val() returns the current value. Save this answer.


1 Answers

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

like image 122
BMH Avatar answered Sep 30 '22 19:09

BMH