0

For some reason, if you have a button in a form, and a text field in a form, pressing enter when the text field has focus results in the button being clicked.

http://jsfiddle.net/cZcGE/

Why does this happen, and how do I make it (the text field) act in a more predictable manner (pressing enter in the text field counts as a keyup event)?

MirroredFate
  • 12,396
  • 14
  • 68
  • 100
  • http://stackoverflow.com/questions/2335553/jquery-how-to-catch-enter-key-and-change-event-to-tab - Check that out. Verify the captured event's key code is 13 (enter key) and then do whatever you want with it. – Jon La Marr Aug 28 '13 at 17:50
  • Thanks, but it really doesn't look like that has anything to do with my question. – MirroredFate Aug 28 '13 at 17:58

3 Answers3

2

Pressing enter in a form is going to attempt to press a button/submit the form. As mentioned in the comments, if you don't want that behavior, you have to capture the keypress and prevent the submission if it was the enter key that was pressed.

In your case, it would be adding this bit of code:

$('input[type="text"]').on('keypress', function (event) {
    if(event.which == 13){
        return false;
    }
});

See: http://jsfiddle.net/cZcGE/8/

keithhatfield
  • 3,273
  • 1
  • 17
  • 24
0

If you want to use a button, it might be better to use an input with button-type.

http://jsfiddle.net/cZcGE/

<form>
    <input type="button" value="bla" />
    <input type="text" />
</form>
0

DEMO

Try this, add onkeydown = "return (event.keyCode!=13);" to the textbox

<input type="text" onkeydown = "return (event.keyCode!=13);"></input>

Hope this helps,Thank you

SarathSprakash
  • 4,614
  • 2
  • 19
  • 35