Prevent submitting form on enter

by Jorge Bustos Pereda

HTML

<div>
    <p>Form 1, default enter behavior, when there is only a textbox, and there is a submit button</p>
    <p>If you press enter, it's submitted</p>
    <form method="GET" id="form1">
        <input type="text" />
        <input type="submit" />
    </form>
</div>

<div>
    <p>Form 2: prevents default behavior on textbox</p>
    <p>If you press enter the form is not submitted</p>
    <form method="GET" id="form2">
        <input type="text" />
        <input type="submit" />
    </form>
</div>

<div>
    <p>Form 3: submit shuld only happen if there is only one textbox, but it depends on the browser</p>
    <p>If you press enter the form should not be submitted, because there are several textboxes, but I bet it will be submitted</p>
    <form method="GET" id="form3">
        <input type="text" />
        <input type="text" />
        <input type="submit" />
    </form>
</div>

CSS

p {
    margin: 0 0 8px 0;
}

div {
    font-family: 'Segoe UI', Verdana, Arial;
    margin: 10px 5px;
    padding: 15px;
    border: solid 1 px #888;
    background-color: #EEE;
}

JavaScript

// This suppres the default behavior of submitting the
// form when the enter key is pressed in the textbox
$('#form2').on('keypress', function (e) {
    if (e.which === 13) {
        e.preventDefault();	
        console.log('key press 13');
    }
});

// This event is triggered when any form is submitted
// (but doesn't send it, becasue of prevent default).
$('form').on('submit', function(e) {
    console.log('Sending form', e.target.name);
    e.preventDefault();
});