Flickr Images

Thursday, April 16, 2020

How can I check if a checkbox in a checkbox array is checked using the id of the checkbox array?

IDs must be unique in your document, meaning that you shouldn't do this:
<input type="checkbox" name="chk[]" id="chk[]" value="Apples" />
<input type="checkbox" name="chk[]" id="chk[]" value="Bananas" />

Instead, drop the ID, and then select them by name, or by a containing element:
<fieldset id="checkArray">
    <input type="checkbox" name="chk[]" value="Apples" />
    <input type="checkbox" name="chk[]" value="Bananas" />
</fieldset>

And now the jQuery:
var atLeastOneIsChecked = $('#checkArray:checkbox:checked').length > 0;
//there should be no space between identifier and selector
// or, without the container:
var atLeastOneIsChecked = $('input[name="chk[]"]:checked').length > 0;

0 on: "How can I check if a checkbox in a checkbox array is checked using the id of the checkbox array?"