views:

642

answers:

4

Is it possible to determine which submit button was used? I have a confirmation form with 2 submit buttons. The first would confirm the order, do some DB tasks, then redirect. The second, which is a Cancel button, will just redirect to the same page, without doing any DB tasks.

Is it possible in the servlet, preferably via the request object, to determine which submit button was used? I'd prefer not to be dependent on Javascript, as that is pretty simple, but will resort to it if the only possibility.

Thanks.

+7  A: 
<button name="someName" value="someValue" type="submit">Submit</button>
<button name="otherName" value="otherValue" type="submit">Cancel</button>

You'll have someName=someValue or otherName=otherValue in your request data

Quassnoi
Thanks. Kind of thought that'd be the case, but just thought I'd ask ahead of time.
Chris Serra
If you already thought that'd be the case, I don't know why you didn't set it up, run it, and test the results? Seems like asking a question you already probably know the answer to is a waste of everyone's time.
abelenky
I don't think it's a waste to hope there's a cleaner way of doing something.
Kev
+6  A: 

Sure, just give each of your submit buttons a name attribute, and whichever one was clicked will appear in the submitted variables:

<input type="submit" name="doConfirm" value="Confirm"  />
<input type="submit" name="doCancel"  value="Cancel"  />
Alnitak
Thanks for your input.
Chris Serra
+1  A: 

As others have mentioned having two buttons with different names will accomplish your goal. However there are some potential problems to be aware of when relying on this in your application. I think they are Internet Explorer specific, so if you don't need to support older versions of IE you might be able to disregard. Both involve the behavior of the submitted form when a user hits enter when one of the form's elements has focus. This article uses ASP to demonstrate the problems but the HTML side of things is relevant.

laz
A: 

When using multiple submit buttons, I like to use javascript to set the value of a hidden form field which describes the action that should take place.

For example:

<input type="hidden" name="action" id="form-action" />
<input type="submit" value="Save" onClick="document.getElementById('form-action').value='save'" />
<input type="submit" value="Copy" onClick="document.getElementById('form-action').value='copy'" />
Clay