Don'tDownvoteMe
Don'tDownvoteMe

Reputation: 511

Checkbox-Select all toggle and also give individual functionality to each checkboxes

I have a list of checkboxes and I want that whenever select all is checked, all the checkboxes should be checked and when it is unchecked, all the checkboxes below should be unchecked. But thereafter I also want if the select all is not pressed then the value of individual checkboxes should be fetched and appended. Select All Toggle is working fine but individual checkboxes get disabled. I want when select all is not pressed, individual values of below checkboxes should get fetched.

$(document).ready(function() {
  $("input[type='checkbox']").click(function() {
    if ($("#chk").is(':checked')) {
      $("input[type='checkbox']").prop('checked', true);

    } else if ($("#chk").not(':checked')) {
      $("input[type='checkbox']").prop('checked', false);


      $("input[type='checkbox']").click(function() {
        $("input[type='checkbox']:checked").each(function() {
          alert($(this).append(this.value));

        })

      })

    }


  })


})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="chk" name="check">Select All<br>
<input type="checkbox" name="check[]" value="mango">Mango<br>
<input type="checkbox" name="check[]" value="cherry">Cherry<br>
<input type="checkbox" name="check[]" value="apple">Apple<br>

Upvotes: 1

Views: 40

Answers (1)

Pedram
Pedram

Reputation: 16615

Your problem is your selector, change $("input[type='checkbox']").click(function() { to $("#chk").click(function() {

$("#chk").click(function() {
  if ($(this).is(':checked')) {
    $("input[type='checkbox']").prop('checked', true);
  } else if ($(this).not(':checked')) {
    $("input[type='checkbox']").prop('checked', false);

  }
});

$("input[type='checkbox']:not('#chk')").click(function() {
  if ($(this).is(':checked')) {
    var val = $(this).val();
    console.log(val);
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="chk" name="check">Select All<br>
<input type="checkbox" name="check[]" value="mango">Mango<br>
<input type="checkbox" name="check[]" value="cherry">Cherry<br>
<input type="checkbox" name="check[]" value="apple">Apple<br>
<div id="selected"></div>

Upvotes: 1

Related Questions