I have a form on my page that is filled with checkboxes the user can select.
The values are paginated on the server, and because of that whenever the user clicks next or previous, new values are loaded in the form and the previous removed.
I have a variable in my script that holds the selected values.
let selectedReaders = new Set();
What I am trying to do, is check if a loaded value has been already selected; and if it has, make it checked.
In the code where I add the HTML for each loaded value, I check if it is and set the checked attribute of the checkbox input to false/true.
But when I open the page, all checkboxes are always unchecked.
Here is the code:
for(let reader of serverReaders){
readers.innerHTML = `
<div >
<input type="checkbox" onclick="addReader(this)" value="${reader.userID}" id="reader-${reader.userID}" >
<label for="reader-${reader.userID}">${reader.username}</label>
</div>`
document.getElementById(`reader-${reader.userID}`).checked = [...selectedReaders].some( id => id === reader.userID)
console.log(document.getElementById(`reader-${reader.userID}`).checked)
}
For each reader, I first add the label and input a checkbox for them, and then I check the selectedReaders variable if it has an id of the reader(which means it has been selected previously).
If it has been selected previously, I check the checked to true otherwise, it is set to false.
The console.log
outputs true for the value if it has been selected previously.
This means that the checked attribute is set to true properly, but on the page, checked=true does not render the input checkbox checked.
What am I doing wrong?
CodePudding user response:
It looks like you are adding the HTML for the checkboxes and setting their checked attribute after they have been added to the page. In this case, the checked attribute is not applied because the elements don't exist yet when you are setting it.
One way to fix this would be to set the checked attribute before adding the HTML for each checkbox to the page. You can do this by storing the HTML for each checkbox in a variable and then setting the checked attribute on that variable before appending it to the page.
Here's an example of how you could do this:
let checkboxHTML = "";
for (let reader of serverReaders) {
// Set the checked attribute on the HTML for the checkbox
let checked = [...selectedReaders].some(id => id === reader.userID);
checkboxHTML = `
<div >
<input type="checkbox" onclick="addReader(this)" value="${reader.userID}" id="reader-${reader.userID}" ${checked ? "checked" : ""}>
<label for="reader-${reader.userID}">${reader.username}</label>
</div>`
}
// Add the checkboxes to the page
readers.innerHTML = checkboxHTML;