views:

61

answers:

3

Hello,

I saw some old code that had:

<input type="submit" name="submit" onsubmit="somefunction(this)" />

I was jQuery'ing the script, how do I get the pure javascript (this) object in jQuery?

$("input[name=submit]").click(function() {
  somefunction(// ?? is it $(this) );
});

Thanks!

+4  A: 

You can just use this, it refers to the clicked object, this is true for any jQuery event handler:

$("input[name=submit]").submit(function() {
  somefunction(this);
});

Or, better would be to use this inside the function, then it's just:

$("input[name=submit]").submit(somefunction);

This won't cover when it's not submitted via the button though, better to do it at the <form> level or via .live() if it's dynamic. Note that by doing this, it'll change this to refer to the <form> instead of the <input>, depending on your function you may need adjustments for that.

Nick Craver
+1  A: 

The submit() event needs to be attached to the form, not the button.

Matt Sherman
Right, fixed, thanks.
Jasie
+3  A: 

It's still this.

The difference between this and $(this) is that this is the DOM element object itself, while $(this) is the DOM element encapsulated in a jQuery object.

BoltClock