0

I have a form with 2 buttons - one is the submit button and the other is a button to apply a discount code. The problem is the Return key always activates the submit button at the bottom of the form.

Is there any way to have the Return key activate the discount code button when the discount code text field is active?

Chris
  • 431
  • 5
  • 11
  • 18

3 Answers3

1

The long and the short is that you'll need to capture either the keyboard event or the submit event of the form. Personally, I think you're better off with keyup.

var discountInput = document.getElementById('discount-input');
var form = document.getElementById('my-form');

function keyupHandler(evt)
{
    if(evt.keyCode == 13 && document.activeElement == discountInput)
    {
        evt.preventDefault();
        evt.stopImmediatePropagation();
        // either trigger the event handler which adds the discount,
        // or call that function here.
    }
}

form.addEventListener('keyup',keyupHandler);
cwallenpoole
  • 79,954
  • 26
  • 128
  • 166
0

Check out this thread:

Trigger a button click with JavaScript on the Enter key in a text box

basically, you attach a key-up listener to the button you want to respond.

Community
  • 1
  • 1
Verran
  • 3,942
  • 2
  • 14
  • 22
  • I did try that but it seems to avtivate both buttons. See here http://jsfiddle.net/RZMCa/ – Chris Jul 19 '13 at 02:24
0

Use autofocus attribute

<input type = "submit" autofocus>
HTTP
  • 1,674
  • 3
  • 17
  • 22