mercredi 28 mars 2018

JQuery - multiple checkboxes actions

I have a form with multiple checkboxes and I would like to get this behavior:

  • The background of the "my_class" parent div changes when a checkbox is checked
  • The top button can Check or Uncheck all checkboxes
  • The background of all the "my_class" divs change when button clicked

CSS, HTML and JS code

$(document).ready(function() {
  $(".check_all:button").toggle(function() {
    $("input:checkbox").attr("checked", "checked");
    $("input:checkbox").closest(".my_class").addClass("checked_bg");
    $(this).val("Uncheck All")
  },
  function() {
    $("input:checkbox").removeAttr("checked");
    $("input:checkbox").closest(".my_class").removeClass("checked_bg");
    $(this).val("Check All");
  });

  $("input:checkbox").on("change", function() {
    var that = this;
    $(this).closest(".my_class").css("background-color", function() {
       return that.checked ? "#bcfab9" : "#ffffff";
    });
  });
});
.checked_bg {
  background-color: #bcfab9;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" class="check_all" value="Check All">
<br>
<br>
<label for="checkbox_1">
      <div class="my_class">
        <input type="checkbox" id="checkbox_1" name="Box[]" value="1">
        <div>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
        <div>Duis sit amet malesuada ligula.</div>
      </div>
    </label>

<label for="checkbox_2">
      <div class="my_class">
        <input type="checkbox" id="checkbox_2" name="Box[]" value="2">
        <div>Quisque magna est, blandit ac laoreet eu, consectetur eget turpis.</div>
        <div>Fusce nisi tortor, suscipit sed luctus eu, varius eget massa.</div>
      </div>
    </label>

Test page: (JSFiddle)[https://jsfiddle.net/o4h97eae/18/]

It doesn't work, would you please help me to sort this out?




Aucun commentaire:

Enregistrer un commentaire