eragon2262 eragon2262 - 4 months ago 11
HTML Question

Can someone explain why my jquery click handler stops working?

I have jquery code that is inside a $(document).ready() call inside an HTML page that loads inside an iframe, and it works correctly until another function is called from the same page that removes a table entry. Then the table reloads still inside the same page but now the click handler to select the table row and highlight it wont work.

This code highlights a row in the table for a function to execute on that row(in this case the issue only happens when removing a row because its the only function that doesn't redirect the page requiring the page to reload after being returned)

On the initial load of the window, the click handler works correctly and will highlight, or un-highlight any row I want. But when I use the function to remove the row is when the issue happens. Here is the code for the highlight function:

$("tr[id*='report']").on("click",function(){
if(!$(this).hasClass("highlighted")){
$("#reports tr").removeClass("highlighted");
$(this).addClass("highlighted");
}
else{
$(this).removeClass("highlighted");
}
});


After the row is removed using a function call from the parent webpage, the page calls the same function used to create the table in the first place to recreate the table with the new rows, but now the click handler for the highlight doesn't work. But the other click handlers for the remove, edit or add buttons still work.

This is the handler to use the edit button to edit the selected report and is located inside the same $(document).ready() function, directly below the highlight function call.

$("#edit").click(function(){
if($("tr").hasClass("highlighted"))
{
openReport(helper);
}
else
{
alert("Please select a report to edit");
}
});


The listener for this button still works, while the highlight function in the same scope does not. And the listener for highlighting does list in chrome's development tools event listeners section.

I am not sure if this is caused by of a scope issue inside the ready function on my part or if I am missing something.
Any ideas or solutions would be great.

If more information is needed feel free to let me know.

Answer

Reading:

...until another function is called from the same page that removes a table entry. Then the table reloads still inside the same page but now the click handler to select the table row and highlight it wont work.

From what I can understand, your problem could be event-binding-on-dynamically-created-elements.

So I suggest to change your function to:

         $(document).on("click", "tr[id*='report']", function(e) {
            if(!$(this).hasClass("highlighted")){
                $("#reports tr").removeClass("highlighted");
                $(this).addClass("highlighted");
            }
            else{
                $(this).removeClass("highlighted");
            }
        });