I have one HTML <form>.
The form has only one action=""
attribute.
However I wish to have two different target=""
attributes, depending on which button you click to submit the form. This is probably some fancy JavaScript code, but I haven't an idea where to begin.
How could I create two buttons, each submitting the same form, but each button gives the form a different target?
I do this on the server-side. That is, the form always submits to the same target, but I've got a server-side script who is responsible for redirecting to the appropriate location depending on what button was pressed.
If you have multiple buttons, such as
<form action="mypage" method="get">
<input type="submit" name="retry" value="Retry" />
<input type="submit" name="abort" value="Abort" />
</form>
Note : I used GET, but it works for POST too
Then you can easily determine which button was pressed - if the variable retry
exists and has a value then retry was pressed, and if the variable abort
exists and has a value then abort was pressed. This knowledge can then be used to redirect to the appropriate place.
This method needs no Javascript.
Note : that some browsers are capable of submitting a form without pressing any buttons (by pressing enter). Non-standard as this is, you have to account for it, by having a clear
default
action and activating that whenever no buttons were pressed. In other words, make sure your form does something sensible (whether that's displaying a helpful error message or assuming a default) when someone hits enter in a different form element instead of clicking a submit button, rather than just breaking.