Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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)) );
like image 579
coderama Avatar asked Sep 03 '25 01:09

coderama


1 Answers

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.

like image 192
Sumit Avatar answered Sep 08 '25 01:09

Sumit