2

I need to redefine the jQuery val() function, but I don't want to mess with the source code. Is it possible to modify it on just one element?

Specifically, I need to do something like this:$("div.smth").val = function() {return this.innerText;};. However, the val function is not modified by this code. What am I doing wrong?

ulu
  • 5,872
  • 4
  • 42
  • 51

4 Answers4

3

You should instead modify the function of the prototype (jQuery calls this fn). This is where all functions like $(...).something inherit from.

$.fn.val = function() { ... };

If you want to save the original function:

var old = $.fn.val; // `old` won't be overwritten

$.fn.val = function() { ... };
pimvdb
  • 151,816
  • 78
  • 307
  • 352
  • How do I call the original function from within the new definition? – ulu Nov 25 '11 at 10:54
  • 1
    @ulu: That's a little more complicated since there is a `this` value that needs to be passed along. You can use `old.call(this, ...)`, which would be equivalent to the previous `$(this).val(...)`. If you want to pass all arguments, you can use `old.apply(this, arguments)`. – pimvdb Nov 25 '11 at 10:56
  • 2
    How does this meet the requirement from the question to "modify it on just one element"? – nnnnnn Nov 25 '11 at 11:34
  • @nnnnnn: You're completely correct, I missed that. In that case, you can check whether the element is the wanted element and if so, do something else. In all other cases, route the call through like `return old.apply(this, arguments)`. – pimvdb Nov 25 '11 at 11:36
2

This will do what you want, you need to attach your new val method to jQuery's plugin stack:

$.fn.val = function(value) {
    return this[0].innerText;
}
Abdul Munim
  • 18,869
  • 8
  • 52
  • 61
0

The other answers indicate how to replace the .val() method, but if you know you only need this for one specific element can't you just do this:

$("div.smth")[0].innerText

But in any case isn't that pretty much what the existing jQuery .text() method does?

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • The point is that I want to use an existing jQuery plugin (autocomplete) with a contenteditable div. So I need to redefine val that is called from that plugin. – ulu Nov 28 '11 at 09:23
0
jsval: function(fn) {
  var that = this;
  var newfn = function(event) { fn.apply(that, arguments); };
  this.click(newfn);
  return newfn;
}

Instead now you can call your normal val and on that specific div, call jsval

Arindam
  • 998
  • 1
  • 8
  • 20
  • The point is that I want to use an existing jQuery plugin (autocomplete) with a contenteditable div. So I need to redefine val that is called from that plugin. – ulu Nov 28 '11 at 09:23