The question is published on by Tutorial Guruji team.
I’m writing code for myself to set values into an array based on which checkboxes are checked.
There is one function for setting innerHTML of the checkbox (checked or unchecked) and second one for changing the value of an array based on the condition if checkbox is checked or not.
The HTML code looks like this:
function check(id) { if (id.innerHTML == "unchecked") { id.innerHTML = "checked"; } else { id.innerHTML = "unchecked"; } } function audiences() { var audiencesLength = []; var checkboxes = []; for (var i = 0; i < 3; i++) { checkboxes.push(document.getElementById("aud" + i).innerHTML) } for (var j = 0; j < 3; j++) { if (checkboxes[j] != "unchecked") { switch (j) { case 0: audiencesLength[j] = 1; break; case 1: audiencesLength[j] = 3; break; case 2: audiencesLength[j] = 7; break; } } else { audiencesLength[j] = 0; } } }
<li class="checkboxes"> <label class="checkbox-container">1 <input type="checkbox"> <span class="checkmark" id="aud0" onclick="check(this)">unchecked</span> </label> <label class="checkbox-container">3 <input type="checkbox"> <span class="checkmark" id="aud1" onclick="check(this)">unchecked</span> </label> <label class="checkbox-container">7 <input type="checkbox"> <span class="checkmark" id="aud2" onclick="check(this)">unchecked</span> </label> </li>
It works until I start to check the checkboxes fast. Then some of them are correct and some of them have values “checked” when unchecked and some of them “unchecked” when checked.
Is there a way to prevent this? Or is there any problem in the code?
Thanks!
Answer
Because you only binding event to span
, which won’t work if you’re click on label
nor input
. Instead, you should use onchange
on input
, this will affect both label of it and itself
function check(element) { id = document.getElementById(element) if (id.innerHTML == "unchecked") { id.innerHTML = "checked"; } else { id.innerHTML = "unchecked"; } } function audiences() { var audiencesLength = []; var checkboxes = []; for (var i = 0; i < 3; i++) { checkboxes.push(document.getElementById("aud" + i).innerHTML) } for (var j = 0; j < 3; j++) { if (checkboxes[j] != "unchecked") { switch (j) { case 0: audiencesLength[j] = 1; break; case 1: audiencesLength[j] = 3; break; case 2: audiencesLength[j] = 7; break; } } else { audiencesLength[j] = 0; } } }
<li class="checkboxes"> <label class="checkbox-container">1 <input onchange="check('aud0')" type="checkbox"> <span class="checkmark" id="aud0">unchecked</span> </label> <label class="checkbox-container">3 <input onchange="check('aud1')" type="checkbox"> <span class="checkmark" id="aud1">unchecked</span> </label> <label class="checkbox-container">7 <input onchange="check('aud2')" type="checkbox"> <span class="checkmark" id="aud2">unchecked</span> </label> </li>