Reputation: 4581
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');
Upvotes: 3
Views: 3900
Reputation: 1
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>
Upvotes: 1
Reputation: 148664
You 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 recommended 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.
Upvotes: 7
Reputation: 87213
TO get the first checked checkbox
find
because checkbox
is not the direct child of ul#checklist
:checkbox
pseudo-selector to get all checkboxesfirst
to get first checkboxUse is(':checked')
to get the checked status
$('#checklist').find(':checkbox').first().is(':checked');
OR
$('#checklist :checkbox:first').is(':checked');
Upvotes: 0