I have two submit buttons in a form. How do I determine which one was hit serverside?
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- Is there a way to play audio on a mobile browser w
- HTML form is not sending $_POST values
- implementing html5 drag and drop photos with knock
Since you didn't specify what server-side scripting method you're using, I'll give you an example that works for Python, using CherryPy (although it may be useful for other contexts, too):
Rather than using the value to determine which button was pressed, you can use the name (with the
<button>
tag instead of<input>
). That way, if your buttons happen to have the same text, it won't cause problems. The names of all form items, including buttons, are sent as part of the URL. In CherryPy, each of those is an argument for a method that does the server-side code. So, if your method just has**kwargs
for its parameter list (instead of tediously typing out every single name of each form item) then you can check to see which button was pressed like this:If you have two submit button with different function then explicitly tell in input buttons with submit type like:
You don't need to worry about which button is called in server side. Write your logic in each function separately and call them. They will do their work without interfering with others.
You can present the buttons like this:
And then in the code you can get the value using:
(valUnits and valPrice are some other values I extract from the form that I left in for illustration)
There’s a new HTML5 approach to this, the
formaction
attribute:Apparently this does not work in IE9 and earlier, but for other browsers you should be fine (see: w3schools.com HTML <button> formaction Attribute).
Personally, I generally use Javascript to submit forms remotely (for faster perceived feedback) with this approach as backup. Between the two, the only people not covered are IE<9 with Javascript disabled.
Of course, this may be inappropriate if you’re basically taking the same action server-side regardless of which button was pushed, but often if there are two user-side actions available then they will map to two server-side actions as well.
Edit: As noted by Pascal_dher in the comments, this attribute is also available on the
<input>
tag as well.Define
name
asarray
.Example server code (PHP):
elseif
very important, because both will be parsed if not. Enjoy.