dimanche 12 mars 2017

Select all checkboxes from div [duplicate]

This question already has an answer here:

I have a form with some checkbox input types, a script to count the checked checkboxes, and I want to have a "button" that selects all of the checkboxes.

My problem is that I can't seem to make the select all "button" to work. Can someone help, please?

$(function() {
  $('#checkbox-count').text(' ');

  var generallen = $("#survey-wrapper input[name='cb']:checked").length;
  if (generallen > 0) {
    $("#checkbox-count").text('(' + generallen + ')');
  } else {
    $("#checkbox-count").text(' ');
  }
})

function updateCounter() {
  var len = $("#survey-wrapper input[name='cb']:checked").length;
  if (len > 0) {
    $("#checkbox-count").text('(' + len + ')');
  } else {
    $("#checkbox-count").text(' ');
  }
}

$("#survey-wrapper input:checkbox").on("change", function() {
  updateCounter();
});

$(function() {
  $('#select-all').change(function() {
    var checkthis = $(this);
    var checkboxes = $(this).parent().next('#survey-wrapper').find("input[name='cb']");

    if (checkthis.is(':checked')) {
      checkboxes.attr('checked', true);
    } else {
      checkboxes.attr('checked', false);
    }
    updateCounter();
  });

})
<script src="http://ift.tt/2eBd7UN"></script>
<span id="checkbox-count"></span>
<input type="checkbox" id="select-all" value=""><label>Select all</label>

<div id="survey-wrapper">
  <form action="">
    <input type="checkbox" id="cb1" name="cb" value=""><label for="cb1">Option #1</label><br>
    <input type="checkbox" id="cb2" name="cb" value=""><label for="cb2">Option #1</label><br>
    <input type="checkbox" id="cb3" name="cb" value=""><label for="cb3">Option #1</label><br>
    <input type="checkbox" id="cb4" name="cb" value=""><label for="cb4">Option #1</label><br>
  </form>
</div>



Aucun commentaire:

Enregistrer un commentaire