Jerod Venema
Jerod Venema

Reputation: 44632

jQuery live preventDefault failing on input elements

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.

Upvotes: 2

Views: 1835

Answers (5)

Sasa
Sasa

Reputation: 129

$('#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;
}

Upvotes: 1

Jerod Venema
Jerod Venema

Reputation: 44632

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.

Upvotes: 1

lonesomeday
lonesomeday

Reputation: 237845

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

Upvotes: 0

Prydie
Prydie

Reputation: 1827

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

Upvotes: -1

jps
jps

Reputation: 11597

Might try an

e.stopPropagation()

Upvotes: 1

Related Questions