2

I need to see if any checkboxes within a range in a fieldset are checked

<fieldset id="issues">
    <input name="A" id="issue_0" type="checkbox" value="A" /> <--- this one
    <input name="B" id="issue_1" type="checkbox" value="B" />
    <input name="C" id="issue_2" type="checkbox" value="C" />
    <input name="D" id="issue_3" type="checkbox" value="D" />
    <input name="E" id="issue_4" type="checkbox" value="E" />
</fieldset>

The field set is #issues, this works fine to see if any of them are checked

if( $('#issues input[type="checkbox"]').is(':checked') ){
  console.log("One of them is checked");
}

But I want to see if a specific checkbox by index is checked, ie if the first one is checked. I tried this...

if( $('#issues input[type="checkbox"][0]').is(':checked') ){
  console.log("Item one is checked");
}

but it doesn't work

How do I target a specific checkbox by index within a fieldset?

Zoltan Toth
  • 46,981
  • 12
  • 120
  • 134
JulianB
  • 1,686
  • 1
  • 19
  • 31
  • http://stackoverflow.com/questions/426258/how-do-i-check-a-checkbox-with-jquery-or-javascript – t q Aug 14 '12 at 23:25

3 Answers3

6
if( $('#issues input[type="checkbox"]').first().is(':checked') ){
    console.log("Item one is checked");
}

Use .first() to grab the first one in the wrapped set.

Also I'd recommend using .prop() as it is easier to deal with when it comes to cross-browser issues!

if( $('#issues input[type="checkbox"]').first().prop('checked') === true ){
    console.log("Item one is checked");
}​

If you needed to get a specific index you could do:

var index = 2;
if( $('#issues input[type="checkbox"]').eq(index).prop('checked') === true ){
    console.log("Item one is checked");
}​
Mark Pieszak - Trilon.io
  • 61,391
  • 14
  • 82
  • 96
3

You can use the eq() method:

Select the element at index n within the matched set.

 if( $('#issues input[type="checkbox"]').eq(0).is(':checked') ){
    console.log("Item one is checked");
 }

or use the :eq() selector:

$('#issues input[type="checkbox"]:eq(0)') // selects the first input
$('#issues input[type="checkbox"]:eq(1)') // selects the second input
Ram
  • 143,282
  • 16
  • 168
  • 197
1

This will allow you to select the nth child:

http://api.jquery.com/nth-child-selector/

if( $('#issues input[type="checkbox"]:nth-child(1)').is(':checked') ){
    console.log("child one is checked");
 }
Hogan
  • 69,564
  • 10
  • 76
  • 117
  • +1. I was interested in comparing execution time between `nth-child` and `eq` and as more inputs you add as faster `nth-child` gets: http://jsperf.com/nth-vs-eq – Nope Aug 14 '12 at 23:34