views:

30

answers:

4

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.

A: 

Might try an

e.stopPropagation()
Jud Stephenson
The `e.stopPropagation()` method usually doesn't do anything for you with `.live()`. Since the event is attached to the `document`, there's really no more event bubbling to stop. Unless there's some use for it in conjunction with `e.isPropagationStopped()`? I can't imagine, though.
patrick dw
@Jud - patrick is correct, live can't stop propagation by definition, since it's attached to the body.
jvenema
Yep, didn't think about using live instead of bind.
Jud Stephenson
A: 

As far as I'm aware the page refresh is a default function of the form not the input button and as such you should be preventing default on the form rather than the input.

Something along the lines of:

$('#target').submit(function() {
  return false;
});
Prydie
A: 

I think forms are submitted on keypress, not on keydown. Try

$('#messages input').live('keypress', function(e){
  if(e.keyCode == 13) {
    alert($(this).attr('value'));
    e.preventDefault();
    return false;
  }
});
lonesomeday
A: 

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.

jvenema