I got a web page with a long table to display data. Using JQuery Tablesorter I made the table sortable.
The last column of the page contains checkboxes (with the class "chk"), to allow the user to select multiple entries. In the table header there is also a checkbox (with the id "checkall" and no class). By clicking this checkbox, the values of all to other checkboxes should flip. As the page needs some time to load fully, I am using the $(window).load()
function (instead of $( document ).ready()
).
I got the following JavaScript code:
$(window).load(function() {
$('#checkall').change(function() {
if ($('#checkall').is(":checked")) {
$('.chk').prop('checked', true);
} else {
$('.chk').prop('checked', false);
}
});
});
This works as expected in Chromium, but not in Firefox. After playing around with the code it seems like the Change-Listener is not even set in Firefox. Nothing that I put into the inner function code is executed on checking the checkbox, while the $(window).load()
function is executed as expected. Same behavior happens when I add an click()
handler instead or using on("change, function(){...})
.
Is this a JQuery bug or am I doing something wrong?
I'm using JQuery 3.6.0 with JQuery Migrate 1.4.1.
Update: I found out that this seems to be a timing issue / race condition. If I reload the page sometimes, it works in Firefox as well in about 1 of 10 tries. But I have still no idea what the cause is and how to fix it.
CodePudding user response:
Here is an approach that uses event delegation. You need an element that is present in DOM at the time document.ready
is fired. Lets say that element is the table. You would write:
$(function() {
$("#the-table").on("click", "#checkall", function() {
// toggle stuff
});
});
In this case the event handler is bound to the table. It will trap all clicks and, if the originator of the event is the checkbox it will fire the callback.