StrugglingCoder
StrugglingCoder

Reputation: 5011

jQuery select and uncheck a checkbox

I have a list of checkboxes in my document.

If I do

$(".myCheckbox input[type='checkbox']")

I see

    jQuery.fn.init(6) [input#myCheckbox1_0, input#myCheckbox2_0, input#myCheckbox2_1, input#myCheckbox2_2, input#myCheckbox2_3, input#myCheckbox2_4, prevObject: n.fn.init(1), context: document, selector: ".myCheckbox input[type='checkbox']"]
0
:
input#myCheckbox1_0
1
:
input#myCheckbox2_0
2
:
input#myCheckbox2_1
3
:
input#myCheckbox2_2
4
:
input#myCheckbox2_3
5
:
input#myCheckbox2_4
context
:
document
length
:
6
prevObject
:
n.fn.init [document, context: document]
selector
:
".myCheckbox input[type='checkbox']"

I want to get a reference to the input#myCheckbox2_2 and uncheck it using jQuery.

I tried

$("input#myCheckbox2_2 input[type='checkbox']").prop("checked",false);

and

$(".myCheckbox input[type='checkbox']")[2].prop("checked",false);

It did not work. What am I doing wrong?

Upvotes: 0

Views: 70

Answers (3)

user8554313
user8554313

Reputation:

Try this one, please.

$(".myCheckbox input#myCheckbox2_2[type='checkbox']").prop("checked", false);

Better use only id, cause id need to be unique.

$("#myCheckbox2_2").prop("checked", false);

I think you have issue with your snippens:

  1. $(".myCheckbox input[type='checkbox']")[2].prop("checked",false);
  2. $("input#myCheckbox2_2 input[type='checkbox']").prop("checked",false);

Here you are trying to find:

  1. 3 element instead of 4. You need to replace [2] with [3]
  2. input inside input. But you have not any nested inputs.

Upvotes: 1

לבני מלכה
לבני מלכה

Reputation: 16251

Use .eq():https://api.jquery.com/eq/

Set 3 inside because input#myCheckbox2_2 in 3rd place

that the reason it does not work:$(".myCheckbox input[type='checkbox']")[2].prop("checked",false);

$(".myCheckbox input[type='checkbox']").eq(3).prop("checked",false)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="myCheckbox">
  <input id="checkBox" type="checkbox" checked="true">
  <input id="checkBox" type="checkbox" checked="true">
  <input id="checkBox" type="checkbox" checked="true">
  <input id="checkBox" type="checkbox" checked="true">
  <input id="checkBox" type="checkbox" checked="true">
</div>

Upvotes: 1

partypete25
partypete25

Reputation: 4413

Your selector name is incorrect. No need for the space and additional value. This should work.

$('input#myCheckbox2_2').prop('checked', false);

Upvotes: 0

Related Questions