Override jQuery .val() function?

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.

Leave a Comment