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

心已入冬 提交于 2020-01-24 22:58:21

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/9948110/how-do-you-determine-which-submit-was-used-to-submit-a-form-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!