Daniel T.
Daniel T.

Reputation: 38400

How do I prevent a jQuery handler on a button element inside a form from executing when the user presses enter?

I have a button element inside a form like this:

<form>
    <input type="text">
    <button>Test</button>
    <input type="submit" value="Submit"/>
</form>

With the following JS:

$('form').submit(function() {
    alert('Form submitted.');
    return false;
});

$('button').click(function() {
    alert('Button clicked.');
});

And the jsFiddle: http://jsfiddle.net/JnnRX/

When the user focuses the text field, types in some text, and presses enter, the button handler will execute first, followed by the form handler. However, I'd like it to just execute the form handler and ignore the button. Is there any way to get this behavior, or is it best to change my button element to something else?

Upvotes: 0

Views: 112

Answers (2)

Jake
Jake

Reputation: 4234

Here you go: http://jsfiddle.net/JnnRX/17/

Basically you just use e.preventDefault() on keyup() for the form. e represents the keyup event, and e.keyCode represents the key that was pressed. 13 is the enter key's keycode.

EDIT: Woops, I didn't understand your original request. I've updated the jsfiddle with what you wanted.

Upvotes: 0

Nick Rolando
Nick Rolando

Reputation: 26177

Make the button of type button

<button type="button">Test</button>

If it is that type, the browser won't recognize "enter" submits, unless that button has focus. Typically the first submit button in a form's flow will be the one to get submitted on enter.

Upvotes: 1

Related Questions