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
});
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.
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.
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.
attr('value') returns the value that was before editing input field. And . val() returns the current value. Save this answer.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With