Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery: Checkbox how to check or uncheck all checkboxes when another checkbox is selected [duplicate]

When i select/unselect selectAll checkbox I want all the other checkbox to be checked or unchecked.

There is no child or parent element

Html Code:

<div>
 <li class="input">
  <input type="checkbox" name="selectAll" value=""></input>
 </li>
 <li class="input">
  <input type="checkbox" name="practice" value=""></input>
 </li>
 <li class="input">
  <input type="checkbox" name="filename" value=""></input>
 </li>
 <li class="input">
  <input type="checkbox" name="comment" value=""></input>
 </li>
</div>

This is what i tried to do so far -

$(this).siblings('ul').find("input[type='checkbox']").prop('checked', true);

and

$(this).parent().find('input:checkbox:first').prop('checked', true);
like image 560
Atish Avatar asked Dec 19 '22 22:12

Atish


2 Answers

Here you go.

Markup:

  <div>
    <li class="input">
      <input type="checkbox" id="select-all" name="selectAll" value=""/>
    </li>
    <li class="input">
      <input type="checkbox" name="practice" value=""/>
    </li>
    <li class="input">
      <input type="checkbox" name="filename" value=""/>
    </li>
    <li class="input">
      <input type="checkbox" name="comment" value=""/>
    </li>
  </div>

Code:

$("#select-all").on("click", function() {
  var all = $(this);
  $('input:checkbox').each(function() {
       $(this).prop("checked", all.prop("checked"));
  });
});

Fiddle: http://jsfiddle.net/PcMnk/148/

like image 178
Saran Avatar answered Feb 22 '23 23:02

Saran


HTML

<div>
    <li class="input">
        <input type="checkbox" class="select-all" name="selectAll" value=""></input>
    </li>
    <li class="input">
        <input type="checkbox" class="item-checkbox" name="practice" value=""></input>
    </li>
    <li class="input">
        <input type="checkbox" class="item-checkbox" name="filename" value=""></input>
    </li>
    <li class="input">
        <input type="checkbox" class="item-checkbox" name="comment" value=""></input>
    </li>
</div>

Jquery

$(".select-all").on("click", function() {
    $(".item-checkbox").prop("checked", $(this).prop("checked"));
});

OR (if you can't assign a class for some reason)

$("input[name=selectAll]").on("click", function() {
    $("input:checkbox").prop("checked", $(this).prop("checked"));
});

OR (if you only want the checkboxes that are at a similar level in the DOM

$("input[name=selectAll]").on("click", function() {
    $(this).closest("div").find("input:checkbox").prop("checked", $(this).prop("checked"));
});
like image 42
kasdega Avatar answered Feb 22 '23 23:02

kasdega