tags:

views:

51

answers:

3

I've got an HTML <form> with a few <button>s and an <input type="submit">:

<form>
    <button>first button</button>
    <button>second button</button>
    <input type="text">
    <input type="submit">
</form>

But when enter is pressed while in the text field, the "first button" is activated instead of the "submit" button.

How can I make enter trigger the "submit" button?

A: 

You can most likely override he default behavior of your text-input via some simple jQuery. Try taking a look at the documentation for .keydown()

sigint
+6  A: 

The default behavior of a <button> element is to act like a 'submit' button. Try using <button type='button'> for the non-submit buttons.

Phil
Ah, beautiful. That's exactly the kind of thing I was hoping for, but couldn't find. Thanks! Oh, and welcome to Stack Overflow :)
David Wolever
+1  A: 

This can be easily done with jQuery, a Javascript Library. To use the features of jQuery, you must download the source code and include it in your HTML <head> tag.

<head>
<script type="text/javascript" src="jQuery.js"></script>
</head>

For a smaller file-size version of jQuery, use this source code. Now, to trigger the submit on "Enter":

$('.input').keypress(function(e) {
    if(e.which == 13) {
        $(this).blur();
        $('#submit').focus().click(); 
    }
    e.preventDefault();
});

... and I would further modify your <form> by adding some classes and ids, but for the above suggestion, make sure to add the class "input" and the id "submit":

<form>
    <button>first button</button>
    <button>second button</button>
    <input type="text" class="input">
    <input type="submit" id="submit">
</form>

Let me know if that works. I hope this helps.

Hristo