I have the following code which returns the values for checkboxes How do I select/unselect all and get all the selected values?
<p><label><input type="checkbox" id="checkAll"/> Check all</label></p>
<div id="checkboxlist">
<div><input type="checkbox" value="1" class="chk"> Value 1</div>
<div><input type="checkbox" value="2" class="chk"> Value 2</div>
<div><input type="checkbox" value="3" class="chk"> Value 3</div>
<div><input type="checkbox" value="4" class="chk"> Value 4</div>
<div><input type="checkbox" value="5" class="chk"> Value 5</div>
<div>
<input type="button" value="Get Value" id="buttonClass">
</div>
</div>
JS
$(document).ready(function () {
/* Get the checkboxes values based on the class attached to each check box */
$("#buttonClass").click(function() {
getValueUsingClass();
});
/* Get the checkboxes values based on the parent div id */
$("#buttonParent").click(function() {
getValueUsingParentTag();
});
});
function getValueUsingClass(){
/* declare an checkbox array */
var chkArray = [];
/* look for all checkboes that have a class 'chk' attached to it and check if it was checked */
$(".chk:checked").each(function() {
chkArray.push($(this).val());
});
/* we join the array separated by the comma */
var selected;
selected = chkArray.join(',') + ",";
/* check if there is selected checkboxes, by default the length is 1 as it contains one single comma */
if(selected.length > 1){
alert("You have selected " + selected);
}else{
alert("Please at least one of the checkbox");
}
}
DEMO: https://jsfiddle.net/zf2obcLd/2/
There are 3 parts, one for getting the checked values:
On click we loop through all the checked checkboxes
input[type=checkbox]:checked
then we add the value to an array.The second part is for check all, we change all the checkboxes to match the property
checked
of the check all box.the third is how you check the "check all" button if they were all manually checked, and un-check it if at least one of them gets unchecked