Given the code below it displays two check-boxes 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 see if the first list item is checked?
ex below:
$('#checklist).child('li label first:input').is(':checked');
Given the code below it displays two check-boxes 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 see if the first list item is checked?
ex below:
$('#checklist).child('li label first:input').is(':checked');
Share
Improve this question
edited Jun 9, 2015 at 13:37
Prasanna
7795 silver badges13 bronze badges
asked Jun 9, 2015 at 13:15
JebathonJebathon
4,60314 gold badges62 silver badges117 bronze badges
1
-
$('#checklist).find("(input:checked):first");
– Khanh TO Commented Jun 9, 2015 at 13:17
3 Answers
Reset to default 7You can check :
$("#checklist :checkbox:first:checked").length>0
Optimization :
To prevent jQuery search *
items , and find only input type , , this should be made :
$("#checklist input:checkbox:first:checked").length>0
From jQuery :
it is remended to precede it with a tag name or some other selector; otherwise, the universal selector ("*") is implied. In other words, the bare
$(':checkbox')
is equivalent to$( "*:checkbox" )
, so $( "input:checkbox" ) should be used instead.
var res = $("#checklist input:eq(0)").is(function() {
return this.checked
});
console.log(res);
<script src="https://ajax.googleapis./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>
TO get the first checked checkbox
- Use
find
becausecheckbox
is not the direct child oful#checklist
- Use
:checkbox
pseudo-selector to get all checkboxes - Use
first
to get first checkbox Use
is(':checked')
to get the checked status$('#checklist').find(':checkbox').first().is(':checked');
OR
$('#checklist :checkbox:first').is(':checked');