title: Use Javascript to change which submit is activated on enter key press
body: <p>I have a form on an HTML page with multiple submit buttons that perform different actions. However, when the user is typing a value into a text input and hit enters, the browsers generally act as though the next submit button sequentially was activated. I want a particular action to occur, so one solution I found was to put in invisible submit buttons into the HTML directly after the text inputs in question, like this:</p>
  
  <pre><code>&lt;input type="text" name="something" value="blah"/&gt;
  &lt;input type=submit name="desired" value="Save Earth" style="display: none"/&gt;
  ...
  &lt;input type=submit name="something_else" value="Destroy Earth" /&gt;
  ...
  &lt;input id="foobar" type=submit name="desired" value="Save Earth" /&gt;
  </code></pre>
  
  <p>This works like a charm in most browsers, except that it doesn't in webkit browsers like Safari and Chrome. For some reason they skip over the invisible submit button. I've been trying to figure out how to intercept the enter key press and activate the proper submission using Javascript, but I haven't been able to get it to work. Intercepting the keydown and setting focus on the proper submit does not work. </p>
  
  <p>Is there any way using Javascript or otherwise to select which submit button will be used when the user hits the enter key in a text input on an HTML form?</p>
  
  <p><em>Edit: To clarify, the form can't require Javascript to "work" fundamentally. I don't care if the enter key submission is undesireable without Javascript on webkit browsers, but I can't remove or change the order of the submit buttons.</em></p>
  
  <p><strike>This is what I tried, it doesn't change the submission behavior in webkit browsers.</strike><br>
  What worked is to change the <em>focus()</em> in the following code to <em>click()</em>.</p>
  
  <pre><code>document.onkeypress = processKey;
  
  function processKey(e)
  {
      if (null == e)
          e = window.event ;
      if (e.keyCode == 13)  {
          document.getElementById("foobar").click(); // previously: focus()
      }
  }
  </code></pre>
  
  <p><strong>EDIT: FINAL SOLUTION:</strong></p>
  
  <p>Works with every browser and only intercepts the enter key when needed:</p>
  
  <p>HTML:</p>
  
  <pre><code>&lt;input type="text" name="something" value="blah" 
      onkeydown="return processKey(event)" /&gt;
  &lt;input type=submit name="desired" value="Save Earth" style="display: none"/&gt;
  ...
  &lt;input type=submit name="something_else" value="Destroy Earth" /&gt;
  ...
  &lt;input id="foobar" type=submit name="desired" value="Save Earth" /&gt;
  </code></pre>
  
  <p>Javascript:</p>
  
  <pre><code>function processKey(e)
  {
      if (null == e)
          e = window.event ;
      if (e.keyCode == 13)  {
          document.getElementById("foobar").click();
          return false;
      }
  }
  </code></pre>