JQuery - find if a child element is checked without referencing its id explicitly?
Given the code below, it displays two checkboxes, and I want to find if the first input (or checkbox) has the "checked" attribute set to true.
<ul id="checklist">
<li id="box1">
<label>
<input id="box_input" type="checkbox"> "A CheckBox" </label>
</li>
<li id="box2">
<label>
<input id="box_input_2" type="checkbox"> "Another CheckBox"</label>
</li>
</ul>
Without referencing the ID of the first checkbox, how can I get jQuery to check if the first item in the list is checked?
ex below:
$('#checklist).child('li label first:input').is(':checked');
source to share
You can check:
$("#checklist :checkbox:first:checked").length>0
Optimization:
To prevent searching for jQuery objects *
and only finding the input type, this should be done:
$("#checklist input:checkbox:first:checked").length>0
From jQuery:
it is recommended to precede it with a tag name or some other selector; otherwise, a generic selector ("*") is assumed. In other words, naked is
$(':checkbox')
equivalent$( "*:checkbox" )
, so $ ("input: checkbox") should be used instead.
source to share
var res = $("#checklist input:eq(0)").is(function() {
return this.checked
});
console.log(res);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id = "checklist">
<li id = "box1">
<label> <input id = "box_input" type = "checkbox"> "A CheckBox" </label>
</li>
<li id = "box2">
<label> <input id = "box_input_2" type = "checkbox"> "Another CheckBox"</label>
</li>
</ul>
source to share
To check the first checkbox
- Use
find
because it ischeckbox
not a direct childul#checklist
- Use a pseudo selector
:checkbox
to get all checkboxes - Use
first
to get the first checkbox -
Use
is(':checked')
to get check status$('#checklist').find(':checkbox').first().is(':checked');
OR
$('#checklist :checkbox:first').is(':checked');
source to share