I have the following snippet of code:
$('#messages input').live('keydown', function(e){
if(e.keyCode == 13) {
alert($(this).attr('value'));
e.preventDefault();
return false;
}
});
where “#message input” is obviously a group of input text elements. I want to catch the “enter” key and prevent it from refreshing the page. However, it fails every time. The alert works fine, but it seems that the preventDefault() isn’t working.
Anyone have any ideas?
Edit: I should have mentioned that I’m working in ASP.NET, and it’s inside a form element. Removing it from the form element solves the problem, but I’d like to know why preventDefault() isn’t working.
Ironically, it was the alert itself that was causing the problem.
AFAICT, the alert would halt the JavaScript execution before the preventDefault() could take effect, but the browser continued processing the keystroke, triggering a form submission.
Weird, but there you have it.