Ionică Bizău
Ionică Bizău

Reputation: 113475

Calling jQuery functions using call or apply

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?

JSFIDDLE

Upvotes: 2

Views: 129

Answers (2)

Barmar
Barmar

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

Gabriel Petrovay
Gabriel Petrovay

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

Related Questions