Search code examples
jquerypreventdefault

jquery preventDefault() is not working sometimes in chrome


I am trying to prevent the default behavior of the enter key through preventDefault() but it is not working.Here is my code

$(document).ready(function(){
 $("#Last").keydown(function(event){
     if (event.keyCode==13) {
      event.preventDefault();
      alert("Enter Pressed");
      }});

 $("#ffff").click(function(event){
        event.preventDefault();
        alert("Submit Button Clicked");
         });
});

and here is the html part

<form action="http://www.google.co.in">
First name: <input type="text" name="FirstName" value="Al"><br>
Last name: <input type="text" id="Last" name="LastName" value="McCoy"><br>
<input type="button" value=" Next " id="validate">
<input id="ffff" type="submit" value="Submit">
</form> 

So according to the code above it should only alert Enter Pressed if I press enter key on Last Name field, but it alerts both.Is there anything in the code wrong? Here is the link for the details Js.do


Solution

  • A. Wolff is correct that this occurs because of the alert() box. This is very very similar to an issue I had in C# and here is the explanation as to why it happens.

    The main thread in Javascript pauses the execution of the specified function when alert is called. It does not, however pause execution of Javascript. So, your second event gets called even though the initial event never finished. This is why the event.preventDefault() does not work. If you run the code below with the console open, you should notice that click gets logged before the exit keydown gets logged.

    The log output I get is:

    Start KeyDown Function
    Start Click Function
    End Click Function
    End KeyDown Function
    

    $(document).ready(function() {
      $("#Last").keydown(function(event) {
        if (event.keyCode == 13) {
          console.log('Start KeyDown Function');
          alert("Enter Pressed");
          event.preventDefault();
          console.log('End KeyDown Function');
        }
      });
    
      $("#ffff").click(function(event) {
        console.log('Start Click Function');
        event.preventDefault();
        alert("Submit Button Clicked");
        console.log('End Click Function');
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <form action="http://www.google.co.in">
      First name:
      <input type="text" name="FirstName" value="Al">
      <br>Last name:
      <input type="text" id="Last" name="LastName" value="McCoy">
      <br>
      <input type="button" value=" Next " id="validate">
      <input id="ffff" type="submit" value="Submit">
    </form>