Linking an Input field to a Button

Is there a way to link an input field to a specific button?

The issue I'm encountering is that if a user pushes 'enter' after filling out an input field, there's no good way (that I've found) of making the enter key hit the correct button. It will either go to the first 'default' button it finds, or simply grab the first button on the page.

Imagine a page laid out as follows:


<button0>

<input1> <button1>

<input2> <button2>


If none of the above buttons are 'default', the enter key will activate 'button0' from both Input1 and Input2. If Button1 is 'default', it will always activate Button1, even if pressing enter with 'Input2' active.

This is obviously problematic if, for example, I have two entry fields on one page. Or if my layout contains any buttons in the header or navigation above the entry fields. 


Is there some way of doing this I'm missing?

Hi Michael,

There's no way to directly associate an input field to a button, but there are ways to accomplish what you have in mind. From what I know, when you press enter, browsers will select a button to submit the form in a non-standardized way (each browser has implemented this behaviour as they see fit).

You can capture a user hitting the enter key in a Javascript event and redirect him to the correct submit with something like this:

 $(html).on('keypress', function(e){
   if ( e.keyCode == 13 ) {
     if( $('#input1').is(":focus")) {
         $('#button1').click();
     } else if( $('#input2').is(":focus")) {
         $('#button1').click();
     }
     //etc
   }
 });

The problem with this approach is twofold: 

 - you're going to have to write a big chunk of Javascript depending on how many inputs and buttons you have in your page;

 - it increases the page maintenance because every time an input or a button is added, you'll need to remember to add them to your keypress event.

Instead of implementing this, have you considered that you might have too many sets of inputs and buttons active on the page at the same time? Could you perhaps control the "course" of the user on the page by having him activate what parts of the form he requires? I'm not aware of your requirements or the nature of the page you're building, but usually this specific problem arises because the page itself has grown too much in complexity.