user1464139
user1464139

Reputation:

Linking the pressing of Enter to a button click with jQuery

I have some bottons on a modal form:

<div class="block-footer align-right">
<button type="button">Submit</button>
<button type="button">Submit &amp; Close</button>
<button type="button">Close</button>
</div>

How can I make it so the when a user clicks on the Enter key then the first of the buttons "Submit" is "clicked". It's important for the click action as I want the user to visually see the color of the button change as it is clicked.

Note that I already did the following and tied the execution of a function to that button:

$('#modal button:contains("Submit")').click(function () {
    submitHandler(dObj.$link, $('#main-form'), false);
}); 

Upvotes: 6

Views: 4560

Answers (2)

Misam
Misam

Reputation: 4389

This will detect 'Enter' key press

$(document).keypress(function(event){

    var keycode = (event.keyCode ? event.keyCode : event.which);
    if(keycode == '13'){
        $('#Submit').click();   
    }

});

Upvotes: 11

fedmich
fedmich

Reputation: 5381

How about handling submit() instead?

$('form#id').submit(function(){

    //some validation

    return false; //dont allow submit
});

Upvotes: 1

Related Questions