-2

Finding the element is one thing, updating a particularly indexed one is the question here.

Given basic HTML for a group of three checkboxes such as

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
Test!!!!!
<input name='cars' type='checkbox' value="primary" checked/>
<input name='cars' type='checkbox' value="secondary"/>
<input name='cars' type='checkbox' value="tertiary"/>
</body>
</html>

I can use jquery to select all the checkboxes with

$("input").prop( "checked", true );

However, how can I target just one checkbox such as the middle one?

I tried

$("input")[1].prop( "checked", true );

But I get prop is not a function

and $("input")[1].prop( "checked", true ); returns [] with no change.

It looks like I found one option which is a nested find, e.g.

$($("input")[1]).prop( "checked", true );

Is there a cleaner way than that?

Michael Durrant
  • 93,410
  • 97
  • 333
  • 497

3 Answers3

1

You have to use .eq(index) at this context,

$("input").eq(1).prop( "checked", true );

If you use bracket notation, then it will return the plain node object. And that doesn't have a function called .prop() in its prototype. So that wont work, will cause error.

And this nesting $($("input")[1]).prop( "checked", true );. It works because $(nodeObject) will be converted into a jquery object so over it you can access jquery functions like prop().

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
1

You can use nth-of-type selector

$("input:nth-of-type(2)").prop( "checked", true );
The Process
  • 5,913
  • 3
  • 30
  • 41
0

Just found that one option is using .checked = false against the first instance ([1]) of the "input" selector, i.e.

$("input")[1].checked = false;
Michael Durrant
  • 93,410
  • 97
  • 333
  • 497