4

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)) );
rockstardev
  • 13,479
  • 39
  • 164
  • 296
  • what you are trying to do `this` on `doSomething` and in which context its not working. – Rahil Wazir Dec 10 '13 at 09:38
  • I'm trying to pass a reference to the selected radio button to the function I created – rockstardev Dec 10 '13 at 09:40
  • 1
    Check these links - [call a function on click event](http://stackoverflow.com/questions/3273350/jquery-click-pass-parameters-to-user-function) [call a function on change event](http://stackoverflow.com/questions/4897368/how-to-use-a-function-that-takes-arguments-with-jquerys-change-method) – Anil Saini Dec 10 '13 at 09:46

5 Answers5

5

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.

Sumit
  • 1,661
  • 1
  • 13
  • 18
0

What about What about

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

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

Dev
  • 6,628
  • 2
  • 25
  • 34
0

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)); } );
Haneev
  • 765
  • 5
  • 6
0

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

ProllyGeek
  • 15,517
  • 9
  • 53
  • 72
0

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

var that = this;
('a.link').change(function (e) { doSomething($(that)); } );
LeGEC
  • 46,477
  • 5
  • 57
  • 104