views:

575

answers:

3

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()

+1  A: 

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.

Reid
+9  A: 

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.

CMS
Thank you, much appreciated.
Roberto Sebestyen
A: 

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.

Florin
I'm sorry, I don't understand your answer. I was asking about how to override .val() not how to implement .val() for check-boxes.
Roberto Sebestyen
I guess I should remove my comment. I was asking a question myself too, not really answering yours.
Florin
@Florin oh okay that makes more sense now. Then I suggest posting a new question so that people can attempt to answer it. Stack overflow does not work well in a discussion format.
Roberto Sebestyen