0

I have a checkbox array and a checkall/uncheck all function. When I uncheck all, I want to make sure the first remains checked but it does not work the way below:

$("input[name='temps[]']").removeAttr("checked");   // works
$("input[name='temps[0]']").prop("checked", true);  // doesn't work

Is there a workaround so that I don't have to hassle with it inside the loop generating checkboxes or I can't do it without e.g. giving the first checkbox an id?

$("#firstBox").prop("checked", true) 
3
  • 1
    Maybe using the first-child selector? Commented Jan 31, 2017 at 8:46
  • Can you post your complete code for better understanding? Commented Jan 31, 2017 at 8:48
  • 1
    Use this $('input[name="temp[]"]:first').prop('checked',true); Commented Jan 31, 2017 at 8:55

4 Answers 4

3

You can use .eq(index ) or :eq(index ) to get the element at specified index, then the desired operation can be performed

$("input[name='temps[]']").eq(index).prop("checked", true); 

OR,

$("input[name='temps[]']:eq(" + index + ")").prop("checked", true); 

You can also use :first selector to get the first matched DOM element

$("input[name='temps[]:first']").prop("checked", true);
Sign up to request clarification or add additional context in comments.

2 Comments

This .eq() is the solution, perfect. I upvoted all answers but it won't show.
Oh I see! I'm gonna make that up for.
1

Look at your HTML source. Element name is temps[] and not temps[0]. That's why second selector does not work.

To select first, use .eq(0):

$("input[name='temps[]']")
    .removeAttr("checked")
    .eq(0)
    .addClass('checked')
    .prop('checked', true)
;

Comments

1

You can use the eq() function to extract an item by number from a jQuery list. This will create a derived list with just that one item, and then you can proceed as usual:

$("input[name='temps[]']").eq(0).prop("checked", true);

Comments

1
$("input[name='temps[]']")[0].prop("checked", true);

Or

$("input[name='temps[]:first']").prop("checked", true);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.