Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redefining a jQuery function

I need to redefine the jQuery val() function, but I don't want to mess with the source code. Is it possible to modify it on just one element?

Specifically, I need to do something like this:$("div.smth").val = function() {return this.innerText;};. However, the val function is not modified by this code. What am I doing wrong?

like image 491
ulu Avatar asked Jul 23 '26 12:07

ulu


2 Answers

You should instead modify the function of the prototype (jQuery calls this fn). This is where all functions like $(...).something inherit from.

$.fn.val = function() { ... };

If you want to save the original function:

var old = $.fn.val; // `old` won't be overwritten

$.fn.val = function() { ... };
like image 93
pimvdb Avatar answered Jul 26 '26 03:07

pimvdb


This will do what you want, you need to attach your new val method to jQuery's plugin stack:

$.fn.val = function(value) {
    return this[0].innerText;
}
like image 41
Abdul Munim Avatar answered Jul 26 '26 03:07

Abdul Munim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!