Search code examples
jquerycheckboxlist

jQuery change only certain index of a checkbox name array


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) 

Solution

  • 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);