January 24, 2011

Multiple Submit Buttons: Changing Order of Default Button

When a form contains more than one submit button, the name-value pair submitted by the browser is that of the button that was activated (via click for example). But what happens if you press "Enter" to submit the form? The answer is simple: the name-value pair submitted by the browser is that of the first submit button that appears in the source.

The following example shows a form with multiple submit buttons and the information posted by the browser when the user submits the form by pressing enter:

<form method="post" action="">
  <div>
    <input type="text" name="text1" value="text box 1"><br>
    <input type="text" name="text2" value="text box 2">
  </div>
  <div>
    <input type="submit" name="submit1" value="&lt; Prev">
    <input type="submit" name="submit2" value="Save">
    <input type="submit" name="submit3" value="Next &gt;">
  </div>
</form>

POST data:

array(3) {
  ["text1"]=>
  string(10) "text box 1"
  ["text2"]=>
  string(10) "text box 2"
  ["submit1"]=>
  string(6) "< Prev"
}

If you want to make the "Next" button behave as the default button, there is one simple way to achieve this: move this button ahead of all other submit buttons defined for the given form in the document source; then use CSS to change how it appears in the browser:

<form method="post" action="">
  <div>
    <input type="text" name="text1" value="text box 1"><br>
    <input type="text" name="text2" value="text box 2">
  </div>
  <div>
    <input type="submit" name="submit3" value="Next &gt;" style="float: right;">
    <input type="submit" name="submit1" value="&lt; Prev" style="float: left;">
    <input type="submit" name="submit2" value="Save" style="float: left;">
    <div style="clear: both;"></div>
  </div>
</form>

Notice how the elements are floated left and right. This pushes the Next button after the other buttons although inside the source it appears before the other buttons. Instead of floating the elements, you can also try relative-absolute positioning, negative margins or any CSS trick that allows you to position elements irrespective of document flow.

POST data when user submits the form by hitting enter:

array(3) {
  ["text1"]=>
  string(10) "text box 1"
  ["text2"]=>
  string(10) "text box 2"
  ["submit3"]=>
  string(6) "Next >"
}

Note: Internet Explorer 8 and prior versions do not (for some strange reason) post the name-value of the submit button when the form is submitted by hitting enter and it contains just one field besides the submit buttons. IE is pants. Period.