23 January 2012

Override jQuery.val() and jQuery.val(value)

Hi all,

Sometimes there are cases when you need to do something when $.val() and $.val(value) from jQuery is called,  but then you still want the default behavior to be kept. Here is an example of how you could do that:

Code:
var originalVal = this.originalVal = $.fn.val;
$.fn.val = function(value) {
    if (typeof value == 'undefined') {
        alert('Getting the value');
        return originalVal.call(this);
    }
    else {
        alert('Setting the value');

        return originalVal.call(this, value);
    }
};


I for example have used it for a jQuery widget, I wanted to override the default behavior of the val()  function when this is performed on the element for which a widget was used. So what I have done is I have added a custom attribute to the element for which I am using the widget and then in the val() I am checking the presence of that attribute - just like below:


Code:
var originalVal = this.originalVal = $.fn.val;
$.fn.val = function(value) {
    if (typeof value == 'undefined') {
        if ($(this).attr('isElementWithWidget')) {
            return $(widgetElementId).val();
        }
        return originalVal.call(this);
    }
    else {
        if ($(this).attr('isElementWIthWidget')) {
            $(widgetElementId).val(value);
        }

        return originalVal.call(this, value);
    }
};


This is all.
Regards,
Roman

2 comments:

Shank said...

thanks ...it helped me a lot....awesome post!

Roman Gherman said...

Glad it was for help for somebody :)

Post a Comment

your thoughts are welcome:

Need more? Leave comments and subscribe to my blog.

.