Barış Velioğlu
Barış Velioğlu

Reputation: 5827

Click closest submit button when any 'enter' key event occurs on any input field

I have multiple submit button on the page. What I want is if user presses enter on any input field it should click the related submit button. I tried the way below but it even couldnt catch the key press on the input fields.

Thanks in advance,

$('* input').keypress(function (e) {

      if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            $(this).closest('input[type=submit]').click();

      }
});

Upvotes: 0

Views: 3703

Answers (2)

artoodetoo
artoodetoo

Reputation: 938

It is not require javascript at all !

Enter key will call "implicit submission" by standards. When multiple input[type=submit] in form, the first one will implicitelly "clicked" by Enter. So, you should place default button to the first.
If you want to swap some buttons, use CSS rules for it.

Some interesting facts about buttons and Enter key is here.

Upvotes: 2

maxijb
maxijb

Reputation: 531

Try this. .closest() won't work unless the submit button is located upside in the DOM tree. Instead you could search for it inside the input's parentNode, or just submit the form (but you probably don't have a form element, because otherwise this would be the default behavior for the enter key).

$(document).ready(function() {
    $('input[type="text"], input[type="password"]').keypress(function (event) {
        if (event.keyCode == '13') { //jquery normalizes the keycode 

            event.preventDefault(); //avoids default action
            $(this).parent().find('input[type="submit"]').trigger('click');
            // or $(this).closest('form').submit();
        }
    });
});

Upvotes: 6

Related Questions