Reputation: 3774
function handleCheckboxClick(event){
if(document.getElementById(event.target.id).checked){
document.getElementById(event.target.id.concat("_visible")).setAttribute("checked", "true");
console.log(document.getElementById(event.target.id.concat("_visible")));
}
}
var requiredCheckboxes = document.getElementsByClassName("checkbox_required");
for (var i = 0, max = requiredCheckboxes.length; i < max; i++){
requiredCheckboxes[i].addEventListener('click', handleCheckboxClick);
}
<table>
<tr>
<th>
Property
</th>
<th>
Visible
</th>
<th>
Required
</th>
</tr>
<tr>
<td>
Email
</td>
<td>
<input type="hidden" name="_email_visible" /><input type="checkbox" name="email_visible" id="donation_email_visible" />
</td>
<td>
<input type="hidden" name="_email" /><input type="checkbox" name="email" class="checkbox_required" id="donation_email" />
</td>
</tr>
</table>
First, click on the required checkbox for Email. As expected the visible box is also checked. Now, check off visible box and click on Required checkbox corresponding to email which will checkoff required box for email. Now click on the required checkbox for email again, the visible checkbox will not be checked. So, here is where my dilemma lies. What is the reason during this second time when clicked on required, why is the visible box not checked? I appreciate your help! Thanks!
Upvotes: 1
Views: 1709
Reputation: 943089
The checked
attribute determines the default state of a checkbox. Changing it with JS will only alter the current state of a checkbox if the user hasn't modified it.
The checked
property determines the current state of a checkbox. Use that instead.
i.e.
Change any instances of setAttribute("checked", "checked")
(nb: true
is not a valid value for that attribute) to checked = true
and any instances of removeAttribute("checked")
to checked = false
.
Upvotes: 6