If an HTML form has two <input type=“submit”>

2019-01-08 17:51发布

问题:

Suppose I have the following HTML form:

<form>
...
<input type="submit" name="queue" value="Queue item">
<input type="submit" name="submit" value="Submit item">
</form>

How do I know which button the user clicked (without using javascript)?

I looked at submitted data and it seems that when "Queue Item" is clicked then "queue" = "Queue Item" gets sent to the server. And when "Submit item" is clicked then "submit" = "Submit item" sets sent.

Can I rely on this behavior? Is it documented somewhere in the standard on HTML forms? How do you guys do it?

回答1:

Yes, you can rely on this; it's fully documented here. The specific relevant lines say:

When a form is submitted for processing, some controls have their name paired with their current value and these pairs are submitted with the form. Those controls for which name/value pairs are submitted are called successful controls.

and

If a form contains more than one submit button, only the activated submit button is successful.



回答2:

Yep you can rely on that behaviour.

When <input type="submit" name="queue" value="Queue item"> is clicked, the field "queue" will be set and "submit" will not be.

Whereas when the other gets clicked, the field "submit" will be set, and "queue" will not be.

If you're not assured by this, you can split them into 2 forms and work on it that way.



回答3:

You can rely on this behavior. You get the value of the input. I would use javascript to toggle a hidden form value, but since you mentioned no javascript you do not have multiple choices.

It's a standard. Since it's an input tag, and has a value, that means you get the value submitted.



回答4:

Split the form into two forms, replicating any other inputs needed by the other action. Or, if you really just need to know if the user wants to "queue vs. submit" the item, change both submit buttons to radio selections to toggle between the two options, and have a new, separate "submit the form" button.

In that situation if you want a one-click option, you could use Javascript to detect when one of the radio buttons is selected, and auto-submit the form instantly. (Using Javascript for user interface, rather than form handling)