Jebathon
Jebathon

Reputation: 4581

jQuery - find if a child input element is checked without referencing its id explicitly?

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

Answers (3)

guest271314
guest271314

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

Royi Namir
Royi Namir

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

Tushar
Tushar

Reputation: 87213

TO get the first checked checkbox

  1. Use find because checkbox is not the direct child of ul#checklist
  2. Use :checkbox pseudo-selector to get all checkboxes
  3. Use first to get first checkbox
  4. Use is(':checked') to get the checked status

    $('#checklist').find(':checkbox').first().is(':checked');

OR

$('#checklist :checkbox:first').is(':checked');

Upvotes: 0

Related Questions