I am writing a custom jquery plugin that basically replicates the functionality of an input. I could explain why, but truthfully the explanation is quite long and I believe it to be irrelevant to the question.
The trouble comes when I try to extend jQuery's .val() method to my custom jquery plugin. Here is what I've tried:
$.fn.custom_text_input = function(options){
return this.each(function(){
var custom_text_input = new CustomTextInput(options, this)
$(this)[0].val = function(){
alert('something useful')
}
})
}
Ive tried a few other variations of this, all to no avail. If anyone has any ideas that will work, I would very much appreciate the wisdom!
Thanks!
To overwrite the $.val()
method you need to do something like $.fn.val = function () {...}
. Here is a demo: http://jsfiddle.net/CRRP5. I would recommend saving the old .val()
method in a variable so you can use it when .val()
is called on a regular form input.
The only way you're going to get this to work is by extending the result of jQuery's val()
method.
$(function(){
$.fn.oldVal = $.fn.val
$.fn.val = function(value){
//I'm assuming here that you're setting/getting a data value
//on the object to keep track of it's "custom value"
if(value && $(this).data('custom-input-value')){
return $(this).data('custom-input-value', value);
}
else if(value = $(this).data('custom-input-value')){
return value;
}else{
return value ? $(this).oldVal(value) : $(this).oldVal();
}
}
})
That might work for you :p
Here's a jsfiddle with it working: http://jsfiddle.net/Z4c6d/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With