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()
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()
If I am understanding you right, something like this should do the trick just fine:
jQuery.fn.val = function (new_val) {
alert("You set a val! How wonderful!");
this.value = new_val;
};
Just make sure you include the regular functionality: getting values of selects and so on. Just stick that code after after the regular jQuery library.
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.
How would you override val() just for 'input:checkbox'?
I find that by having val() return 'on' invariably when applied to checkboxes is odd behavior. Most of the time, the checkbox 'value' attribute is never set and the only relevant information is 'checked' or not. $('').val() should verify if the attr 'value' is defined, and if not, return the check status, else return the 'value' value.
So I tried this:
(function ($) {
var originalVal = $.fn.val;
$.fn.val = function(value) {
if ($(this).is(':checkbox')) {
return $(this).is(':checked');
};
return originalVal.call(this, value);
};
})(jQuery);
My problem I have now, is that I do not know how to determine if the 'value' attribute is set. Using $(this).attr('value') returns 'on' always.
Thanks for the help.