Question

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.

Was it helpful?

Solution 2

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.

OTHER TIPS

Might try an

e.stopPropagation()
$('#form_deal_step1').live('submit',function(){
        $('.column .column_child select').not(':hidden').each(function(ev){
             if($(this).val()=='?')
             {
                 alert('Please select the ages of each child.');
                 ev.preventDefault();
                 return false;
             }
          });
})
var age_selected=1;
$('.column .column_child select').not(':hidden').each(function(){
    if($(this).val()=='?')
    {                
        age_selected=0; 
    }
});
if(age_selected==0)
{
    alert('Please select the ages of each child.');
    return false;
}

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;
  }
});

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;
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top