Created
October 16, 2014 11:58
-
-
Save aruseni/6614d7330c36cdfc9b71 to your computer and use it in GitHub Desktop.
Chain set checkboxes in group when “Select” all checkbox is changed/“Select all” checkbox when checkboxes in group are changed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta http-equiv="content-type" content="text/html; charset=UTF-8"> | |
<title>Coffee shop</title> | |
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> | |
<script type="text/javascript" src="checkboxes.js"></script> | |
</head> | |
<body> | |
<p>What topping would you like?</p> | |
<div class="checkboxes"> | |
<label><input id="all" type="checkbox"> All of ’em!</label> | |
<div class="toppings"> | |
<label><input type="checkbox"> Vanilla Ice Cream</label> | |
<label><input type="checkbox"> Mango Syrup</label> | |
<label><input type="checkbox"> Cherry Chocolate Creamer</label> | |
<label><input type="checkbox"> Cinnamon</label> | |
</div> | |
</div> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// If the user checks the “Select all” checkbox, check all the checkboxes of the group | |
// If the user unchecks it, uncheck all the checkboxes | |
function chain_set_group_checkboxes_on_all_checkbox_change(checkboxes_of_the_group, all_checkbox) { | |
checkboxes_of_the_group.prop("checked", all_checkbox.is(':checked')); | |
} | |
// If all checkboxes are checked, check the “Select all” checkbox as well | |
// If there are some unchecked checkboxes in the group, then uncheck the “Select all” checkbox | |
function chain_set_all_checkbox_on_group_change(checkboxes_of_the_group, all_checkbox) { | |
all_checkbox.prop("checked", checkboxes_of_the_group.not(':checked').length == 0); | |
} | |
$(document).ready(function() { | |
var all = $("div.checkboxes input#all"); | |
var group = $("div.checkboxes div.toppings input"); | |
all.change(function() { | |
chain_set_group_checkboxes_on_all_checkbox_change(group, all); | |
}); | |
group.change(function() { | |
chain_set_all_checkbox_on_group_change(group, all); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment