rxmnnxfpvg
rxmnnxfpvg

Reputation: 30993

Javascript this in jQuery

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!

Upvotes: 1

Views: 111

Answers (3)

BoltClock
BoltClock

Reputation: 723729

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.

Upvotes: 3

Matt Sherman
Matt Sherman

Reputation: 8358

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

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630439

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.

Upvotes: 4

Related Questions