Joe
Joe

Reputation: 8042

How do you determine which submit was used to submit a form with jQuery?

Keep in mind that the user does NOT have to click the submit nput. They could tab over to it and push enter.

So considering all ways a form can be submitted, how can you determine which one was used to submit the form inside the submit event. I have different names on the two submit elements.

Upvotes: 1

Views: 170

Answers (2)

Pointy
Pointy

Reputation: 413712

Any action that triggers a submit button — be it an actual mouse click or some keyboard action — still triggers a "click" event and still causes the input to be included as a form parameter.

That is, if you see a form parameter with your input field's name and value, you know that that submit button was clicked.

edit — if the form submit happens because you hit "Enter" in a text field, the browser picks the first submit button (I think; that seems to be what Firefox does at least). (Wait; scratch that; Firefox seems to find the next "submit" input after the element that had focus when "Enter" was pressed ...)

Thus:

<form action='whatever' method='post'>
  <input type='text' name='text'>
  <input name='submit1' value='submit1' type='submit'>
  <input name='submit2' value='submit2' type='submit'>
</form>

Hitting "Enter" in the text field would result in "submit1=submit1" being a form parameter, as would hitting "Enter" when "submit1" had focus. Tabbing to "submit2" and hitting "Enter" would result in "submit2=submit2" being among the parameters.

In either case, only one of the "submit" inputs shows up in the parameter list.

Upvotes: 4

imsky
imsky

Reputation: 3279

Instead of using different names, use different values, e.g:

<input type="submit" name="submit" value="Submit A">
<input type="submit" name="submit" value="Submit B">

You can also use buttons instead of inputs if you'd like the labels to be different from the values.

Upvotes: 1

Related Questions