Click here to Skip to main content
15,896,154 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Why does one enter keypress runs (inside) through this code twice?
I've tried keypress, keydown and also event.preventdefault() to no avail.

JavaScript
    $(document).keydown(function (e) {
        if (e.which == 13) {
           alert("0")
            var focado = document.getElementById(document.activeElement.id), fim = focado.id.substring(1),
                inicio = focado.id.substring(0, 1),
                fimseg = fim,
                anterior = inicio + (fim - 1),
                
            alert("1")
            
        
            alert("focado " + focado.id + " fim " + fim + " inicio " + inicio + " fimseg " + fimseg + " anterior " + anterior);
        }
});


and only after giving this 3 messages twice it would continue to the remaining code I trimmed and isn't shown.

thanks
Posted
Comments
Sergey Alexandrovich Kryukov 29-Oct-15 15:08pm    
Use some JavaScript debugger and you will see. And better don't write code in so hard-coded (ad-hoc) style.
—SA
Mohibur Rashid 29-Oct-15 20:12pm    
There is a chance that you have called $(document).keydown(...) twice .

Open your firefox or chrome browser, (there is other but, I don't care that much), and write the following code

i=1;
$(document).keydown(function(e){console.log("here"+i);i++;})
$(document).keydown(function(e){console.log("here"+i);i++;})

and then perform your test and see what happened. you will find your reason

1 solution

Please use the code
It can helps you to prevent immediate twice execution of the event
JavaScript
$(document).keydown(function (e) {
  e.stopImmediatePropagation();
  ......
  ......


Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900