Prevent form Ubmit, but allow other actions by typing enter in an input

Asked

Viewed 276 times

2

I have a input text within a form, however I do not want the form is keyed ENTER. The code below works, but if I decode the alert the form is submitted even having the two lines below. Can anyone explain to 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, while typing ENTER the input will have the same behavior as button click https://jsfiddle.net/o0mkjnwk/

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

Code working: https://jsfiddle.net/o0mkjnwk/1/

I thank everyone who contributed.

  • Which browser are you testing on? Having or not alert(); should not make a difference in behavior. You can make a jsFiddle that shows the behavior?

  • They suggested to use a newer version of the plugin and replace the keydown with . on('keypress'). Follow https://jsfiddle.net/ysj6uk54/

2 answers

2

Utilize setTimeout to solve.

Problem: You’re using the right event to capture the key (keydown), the problem is in the Alert, When it is fired, your control loses focus, and at this point you have not yet returned false to the action of the event. With that is fired the other event (keyup) and the false return is lost, with this is made the Submit.

Use:

setTimeout(function(){ alert("enter"); }, 10);
  • the problem is that actually Alert is only for testing, what I will do when typing enter is a $.get() on another page, which will make a query in the bank, save the return in the session and right after the get the reload page showing the session data. This is what the button that accompanies the input already does https://jsfiddle.net/o0mkjnwk/

  • try to always use the console.log to do this type of test, it will influence much less your tests as it will not trigger events.

1


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

stop();

$(document).ready(function() {
  $('#txtPesquisaServidor').keydown(function(event){
      if(event.keyCode == 13) {
          alert('enter');
          event.preventDefault();
          stop();
      }
  });
});
  • tried here and worked on the plugin version I’m using too, thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.