Specifying a default form submit button that works with Safari

When you have a HTML form with multiple submit buttons, if the user hits their Enter button, it’ll submit the form and pretend that the first submit button in the form was clicked. Given that the button can have name and value attributes, the server can use this information. For example:

<button name="command" value="save">Save</button>
<button name="command" value="delete">Delete</button>

Unfortunately it’s not always possible to put the button you want to be default first in the DOM. A common hack [1] is to use CSS to either float or absolutely position the default button to appear where you want it. In this case you can put a hidden button at the top of the form that is a duplicate of the one visible to the user, e.g.

<form>
  <div style="display:none">
    <button name="command" value="save">This is a duplicate save button</button>
  </div>

  <button name="command" value="delete">Delete</button>
  <button name="command" value="save">Save</button>
</form>

This works well, except in mobile Safari. It seems that because the duplicate button is hidden, the browser ignores it when the user hits Enter. To fix this, instead of using style=”display: none”, absolutely position it off the screen, e.g.

<form>
  <div style="position: absolute; top: -10000px; left: -10000px;">
    <button name="command" value="save">This is a duplicate save button</button>
  </div>

  <button name="command" value="delete">Delete</button>
  <button name="command" value="save">Save</button>
</form>

And there you have it, a nasty hack to work around the fact there is no way to explicitly specify the default button.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s