rockstardev
rockstardev

Reputation: 13527

How to pass parameter when doing Jquery change with function name only syntax?

If I have a function:

function doSomething() {
   ///
}

I can use this with .change as follows:

$("input[name='bla']").change(doSomething);

However, what if the function was:

function doSomething(bla) {
   ///
}

And I wanted to pass "this" as a parameter to the function? This doesn't seem to work:

$("input[name='bla']").change(doSomething(this));

Any ideas?

UPDATE

I do not want this:

$('a.link').change(function (e) { doSomething($(this)); } );

I want this: (but the correct syntax that will work)

$('a.link').change( doSomething($(this)) );

Upvotes: 4

Views: 10390

Answers (5)

LeGEC
LeGEC

Reputation: 51850

The usual solution is to use a variable in the closure scope :

var that = this;
('a.link').change(function (e) { doSomething($(that)); } );

Upvotes: 0

Sumit
Sumit

Reputation: 1669

http://api.jquery.com/change/ and all other jquery events have a variation of the event handler that accepts eventData as the first param.

.change( [eventData ], handler(eventObject) )

But in this case your handler function would look for eventData in the eventObject

http://api.jquery.com/event.data/

So your function would look something like this to use this variation.

var that = this;
$("input[name='bla']").change({otherThis:that}, doSomething);

function doSomething(e) {
   var $this = $(this);
   var otherThis = e.data.otherThis;
}

I added

var $this = $(this);

to show that

$this

is the

$("input[name='bla']")

that was changed. Hope that helps.

Upvotes: 5

ProllyGeek
ProllyGeek

Reputation: 15836

Using jQuery you refer to this using $(this) , but pay attention it will be passed as an object !!

Upvotes: 0

Haneev
Haneev

Reputation: 775

jQuery automatically bind the function call with this. You don't have to pass $(this) on. Only if you want to parse the context of its parent to the function.

For example:

$('a.link').change(function (a) {
     console.log(a); // is event object
     console.log($(this)); // is the same as one match of $('a.link'). `this` is binded to the element 
});

(after comment) Or else you can try:

$('a.link').change(function (e) { doSomething($(this)); } );

Upvotes: 0

Dev
Dev

Reputation: 6776

What about What about

$("input[name='bla']").change(doSomething($(this)));

I think you can refer objects using $(this) in jquery.

Upvotes: 0

Related Questions