Reputation: 113475
I have the following HTML:
<input type="text">
I want to set the value of this input:
$("input").val.call (this, "hi");
jQuery throws an error:
Uncaught TypeError: undefined is not a function
Why is this happening? How can I call a jQuery function using apply
or call
?
I guess the problem is this
that is window
in case above. What value must take this
here?
Upvotes: 2
Views: 129
Reputation: 782508
You can do it like this:
$.fn.val.call($("input"), "hi");
All jQuery methods can be found as $.fn.METHOD
. When you call them the normal way, the jQuery object is the context; when you use .call()
you have to pass the context explicitly as the first argument.
Upvotes: 4
Reputation: 21944
You problem is that this
.
The scope should be the jQuery object $("input")
. So:
var myThis = $("input");
myThis.val.call (myThis, "hi");
The undefined
problem is that jQuery internally will try to call other jQuery functions on that scope object. And your this
(that is probably window
) does not have them.
Upvotes: 4