I have a group of checkboxes that are dynamically generated by php and I am trying to validate at least one is checked and use html5 for validation. My PHP fall back validation is working but my Javascript part is not. I only want to use Javascript for my solution but I am not that great at it.
I am using code from two examples I found on SO. How can I check a checkbox when another checkbox is checked? [JavaScript] Using the HTML5 "required" attribute for a group of checkboxes?.
I was able to get it working with using one set of check boxes as an example but once I tried to loop over the full array of generated checkboxes it failed.
This worked somewhat but only worked if I checked the first checkbox Equipment.
function onToggle(){
if (document.querySelector('#skillset').checked) {
// if checked
console.log('checked');
document.getElementById("radio-for-checkboxes").checked = true
} else {
// if unchecked
console.log('unchecked');
}
}
Page HTML
<div class="checkboxs-wrapper">
<input id="radio-for-checkboxes" type="radio" name="skillset[]" value="2" required/>
<!-- BEGIN parentblockid -->
<p><a onclick="showLinks(['box2','boxlink1','boxlink3','boxlink4','boxlink5','boxlink6','boxlink7','boxlin k8','boxlink9','boxlink10']); hideLinks(['boxlink2','box1','box3','box4','box5','box6','box7','box8','box9','box10'])" class="boxlink" id="boxlink2">{parentblockid.SBB_TITLE}</a></p>
<!-- END parentblockid -->
<div id="box2" style="display:none;">
<!-- BEGIN skillsetsa -->
<input type="checkbox" name="skillset[]" id="skillset" value="{skillsetsa.SBB_VALUE}" {skillsetsa.SBB_VALUECHECKED} data-role="none" required onclick="onToggle()"> {skillsetsa.SBB_TITLE}</p>
<!-- END skillsetsa -->
</div>
</div>
Generated HTML
<div class="checkboxs-wrapper">
<input id="radio-for-checkboxes" type="radio" name="skillset[]" value="2" required/>
<div style="display:none;">
<input type="checkbox" name="skillset[]" value="Equiptment" >Equiptment <br />
<input type="checkbox" name="skillset[]" value="Housing" >Housing <br />
<input type="checkbox" name="skillset[]" value="Other" >Other <br />
</div>
I then tried to loop through the checkbox and find at least one regardless if its the first box or not but it's not working. Any help on this will be greatly appreciative. Thanks.
function onToggle(){
var checkboxs=document.getElementsByName("skillset");
for(var i=0,l=checkboxs.length;i<l;i++){
if (document.querySelector('#skillset').checked) {
// if checked
console.log('checked');
document.getElementById("radio-for-checkboxes").checked = true
}
}else {
// if unchecked
console.log('unchecked');
}
}