Prevent submit form, but allow other actions when typing enter in an input

2

I have input text within form , however I do not want form to be typed ENTER . The code below works, but if I uncomment the alert the form is submitted even with the two lines below. Can anyone explain me why?

$(document).ready(function() {
    $('#txtPesquisaServidor').keydown(function(event){
        if(event.keyCode == 13) {
            //alert('enter!');
            event.preventDefault();
            return false;
        }
    });
});

I'm using jQuery 1.6.2

EDIT 1 The alert is only illustrative, by typing ENTER the input will have the same behavior as the click of the button link

EDIT 2 I got it! If I were to use alert , I would have to set timeout or use stop() so that the code would not be confused, thus sending form (which was not what I wanted). The problem, in fact, does not exist without alert . I just put my original code to test and it worked fine.

Code working: link

Thanks to all who contributed.

    
asked by anonymous 25.09.2015 / 22:00

2 answers

1

I believe it is not the best solution, but it worked here, using

  

stop ();

$(document).ready(function() {
  $('#txtPesquisaServidor').keydown(function(event){
      if(event.keyCode == 13) {
          alert('enter');
          event.preventDefault();
          stop();
      }
  });
});
    
25.09.2015 / 22:24
2

Use setTimeout to solve.

Issue: You are using the right event to capture the keydown , the problem is in alert , when it is triggered, your control loses focus , and at this point you have not yet returned false to the action of the event. With this the other (keyup) event is triggered and the false return is lost, so submit is made.

Use:

setTimeout(function(){ alert("enter"); }, 10);
    
25.09.2015 / 22:26