Scottie Scottie - 1 year ago 73
jQuery Question

jQuery is calling my live("keydown") event multiple times after .load()

I have the following jQuery event:

$("#scanItem").live("keydown", function (e) {
if (e.keyCode == 13) {

scanItem is a textbox in my page.

The first time I load the page, everything works fine. Pressing enter fires the event exactly 1 time. However, I have a dropdown that will do a jQuery load to re-load the div.

After the div reloads, when I press enter on the textbox, the alert fires 3 times.

I've been scratching my brain for hours on this. Any ideas why this is happening?

Answer Source

If the script is reloaded, then you're adding event handlers each time.

An easy solution, if you can't move the script out of the div, would be to change it to not use live :

$("#scanItem").on('keydown', function (e) {

To make it work you must ensure the code is after the #scanItem element.

So this wouldn't touch future elements with the same id.

By the way, as live was deprecated and is now removed from new versions, you really should use on instead, directly (like here) or by delegation (which makes it functionally equivalent to live).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download