Is there a way to easily override jQuery\'s val() function?
The reason I want to override it is that I want to add some processing each time a value is
I know it's an old subject but it's first in google search and the answer is not completely right...
For example if you try in the console $('#myinput').val() you should get the value of #myinput.
But if you do $('#myinput').val(undefined) you should set the value of #myinput!(
With the current answer and the comments of it, you will not set the value of #myinput)
Here is an upgraded answer that use arguments.
(function ($) {
var originalVal = $.fn.val;
$.fn.val = function(value) {
if (arguments.length >= 1) {
// setter invoked, do processing
return originalVal.call(this, value);
}
//getter invoked do processing
return originalVal.call(this);
};
})(jQuery);
if you want to pass all the arguments you can also use apply
(function ($) {
var originalVal = $.fn.val;
$.fn.val = function(value) {
if (arguments.length >= 1) {
// setter invoked, do processing
} else {
//getter invoked do processing
}
return originalVal.apply(this, arguments);
};
})(jQuery);
I hope it help!