1

Possible Duplicate:
Prevent Users from submitting form by hitting enter

I wrote some simple code (you can also test it here )

<form >
       <input id="id2" type='text' />
</form>
$("#id2").keydown(function(e) {
    if (e.keyCode == 13) {
        alert('nope!');
        return false;
    }
});

If I click enter I should see an alert with "nope!" and then nothing. But, after I click "ok" on the alert window, the form is submitting despite the function returning false.

What is it? Something strange multithreading in javascript? Bug? Or...

Community
  • 1
  • 1
Seldon
  • 102
  • 7

1 Answers1

2

Use the keypress event rather than the keydown event:

$("#id2").keypress(function(e) {
    if (e.keyCode == 13) {
        alert('nope!');
        return false;
    }
});

Updated demo

Anthony Grist
  • 38,173
  • 8
  • 62
  • 76