Reputation: 59
So I'm working on a project with electron, and I need to be able to display data in tables, and the user would navigate through the tables using ArrowKeys (for example). In every table there would be some checkboxes for the user to make some choices, and then he would go to the next table. Eventually, it would be possible for him to go back to the previous table, where the choices he made would still be saved. The checkboxes have some onclick function that i would like to be able to keep from one table to the other.
So I came up with this bit of code :
ipcRenderer.on('previousTable', (e) => {
let $upper = $('#upper').clone(true);
let $lower = $('#lower').clone(true);
HTMLBuffer[index] = {
'upper': $upper,
'lower': $lower
};
$('#upper').empty();
$('#lower').empty();
index--;
let previousTableData = allData.find(i => i == index);
if (HTMLBuffer[index]) {
$('#upper').html(HTMLBuffer[index].upper);
$('#lower').html(HTMLBuffer[index].lower);
} else {
makeNewTable(previousTableData);
}
})
The same exists for the 'nextTable' event.
The click event is set up for each checkbox when the first table is displayed, it dynamically change some numbers/colors when the user checks the box, and reverts the changes when he unchecks it. To do this I just use a simple for loop :
checkboxes = tBodyUpper.getElementsByTagName("input");
for (var i = 0; i < checkboxes.length; i++) {
let checkbox = checkboxes[i];
checkbox.onclick = function (event) {
//some color/text changements
}
(Note that I didn't use jQuery here, that part of the code was there before i tried to use jQuery, it will eventually be changed later)
The problem is : the HTML Code is saved and displays perfectly when the user goes back, even the checked boxes remain checked, but the onclick function just won't copy ... I'm very new to jQuery (only this morning tbh, for that specific functionality) so any bit of help would be greatly appreciated !
Upvotes: 0
Views: 89
Reputation: 33933
That definitely is a delegation issue. You run attach the click handlers on page load. So when the checkboxes are "replaced" by the prev/next table function, the elements that were attached do not exist anymore.
You use jQuery, so try it like this:
$(document).on("click","input:checkbox",function(){
//some color/text changements
});
So now, the handler is attached to document
which "delegated" the actions on its child matching the selector (the second argument of the .on()
method).
Instead of attaching it to the document
, it is a good practice to use the closest static parent selector... Like the table container. But you can use document
to test my solution.
Upvotes: 1