Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: textbox keyup firing twice

Tags:

jquery

bind

I'm having a textbox and assigned the following function (it's the only function assigned):

txt.bind("keyup",function(event){
    if(event.keyCode==13)
    {
        var nu = $("#debug").html();
        nu+="<br>enter";
        $("#debug").html(nu);
    }
});

The strange thing is that it's actually firing twice, thus displaying "enter" twice in my debug window. Does anyone know what is causing this?

like image 424
Fuxi Avatar asked Mar 05 '10 14:03

Fuxi


4 Answers

I'm embarrassed to even mention this, but I was typing a capital letter into my textbox and so the release of my shift key was causing the supposed "second firing" of the keyup event. Turns out it wasn't a second firing at all, but it just fooled me into thinking it was for while. At first I thought the unbind trick mentioned above simply wasn't working for me, but it was. I hope this helps others like me that might have done the same thing. Now I simply make sure I always check that its not just the shift key being released in the handling of my event and all is well again.

like image 143
Wade Price Avatar answered Sep 28 '22 06:09

Wade Price


I know it's been quite awhile, but I'm surprised nobody suggested:

txt.unbind();
txt.bind("keyup",function(event){
    if(event.keyCode==13)
    {
        var nu = $("#debug").html();
        nu+="<br>enter";
        $("#debug").html(nu);
    }
});

If somehow txt got bound already, calling unbind before your new bind should fix it. Of course it's preferable to figure out why it's being bound twice. This just happened to me, because I accidentally had my JavaScript file included twice. Calling unbind helped me determine that was the problem.

like image 38
Dave Avatar answered Oct 28 '22 20:10

Dave


i found out by myself - txt.bind was assigned twice to the textbox so it fired twice. is this a bug? i thought binding a function will always fire just once .. hmm

like image 3
Fuxi Avatar answered Oct 28 '22 18:10

Fuxi


I'm having the same issue - keyup and keydown events are being fired twice though their handlers are bound only once and I'm definitely attaching them to only one element.

The interesting point is that this behavior can be observed only in Internet Explorer and in just one special case where my webapp is displayed in an embedded ActiveX control (CLSID_InternetExplorer). OS: Windows 7, IE 8, embedded ActiveX control is running in IE7 compatibility mode.

I've found a workaround however - process the jQuery's keypress event, which made also more semantic sense in my webapp.

like image 2
martinsb Avatar answered Oct 28 '22 18:10

martinsb