Override jQuery .val() function?
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 set for an element. And I don't want to make another custom value setter, such as myVal()
.
Solution 1:
You can store a reference to the original val
function, then override it and do your processing, and later invoke it with call
, to use the right context:
(function ($) {
var originalVal = $.fn.val;
$.fn.val = function(value) {
if (typeof value != 'undefined') {
// setter invoked, do processing
}
return originalVal.call(this, value);
};
})(jQuery);
Note that you can distinguish between a getter call $(selector).val();
and a setter call $(selector).val('new value');
just by checking if the value
argument is undefined
or not.
Solution 2:
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!