Reputation: 3804
What I want to do is to change the default jquery method of a specific element.
For example, I want to change the method val()
of some (not all) select
list. And after that revert back if necessary.
My first attempt is the following but not work.
$('#list').val = function(){ alert('toto'); };
//and then
$('#list').val() //not work
SOLUTION
var old_val = $.fn.val;
$.fn.val = function(value){
//some condition to trigger
if (this.hasClass('someclass')){
//getter
if (value===undefined){
//do something to get the values
return val;
}
//setter
else {
//do something with the value
return this;
}
}
return old_val.apply(this, arguments);
};
Upvotes: 1
Views: 688
Reputation: 10658
Each time you call $('#list')
you're creating a new jQuery object. So when you do $('#list').val = function(){ alert('toto'); };
, you have overwritten the val() method for only that instance. If you cache that object, you could continue to use the overwritten val() method:
var list = $('#list');
list.val = function(){ alert('toto'); };
list.val(); //alerts 'toto'
HOWEVER, this is a bad practice, since you don't know what else will be depending on val() working correctly. The better approach would be to create your own plugin:
$.fn.totoVal = function() {
alert('toto');
return this;
};
You could then call this as $('#list').totoVal()
EDIT
If you really, really want to do this (again it is a bad idea), you can override the native val() implementation this way:
var originalValueFunct = $.fn.val;
//update value function
$.fn.val = function () {
return "custom value";
}
//do something with val()
//restore value function
$.fn.val = originalValueFunct;
See this working demo for an example of overriding and restoring the native val() function.
I strongly advise against doing this as you will create side-effects in your code or any libraries you use that rely on the val() method. These side-effects will be very hard to debug because they will only be present in your environment and it won't always be obvious that you have changed a piece of core jQuery functionality.
Upvotes: 4
Reputation: 992
jquery provides the valHooks object to which you can attach whatever function you would like to attach to the .val() function. Your example would look something like this, to put it in one line.
$.valHooks.select = {get: function( elem ) { if($(elem).attr('id') == 'list') alert('toto') }}
For more detail on valHooks you can look at the jquery api documentation at http://api.jquery.com/val/
Upvotes: 1