Get selected checkbox values
In this article, we will see how to get all the selected checkboxes in array. Before implementing this functionality in your webpage, make sure you have added the JQuery file:
1 2 3 4 5 |
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script> <script src="http://code.jquery.com/ui/1.9.1/jquery-ui.min.js" type="text/javascript"></script> |
Let’s consider we have below piece of HTML code :
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<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 Using Class" id="buttonClass"> <input type="button" value="Get Value Using Parent Tag" id="buttonParent"> </div> </div> |
Below is the JQuery or JavaScript snippet:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
/*Add two click handlers to the button once the page has been fully loaded.*/ $(document).ready(function () { /* Get the checkbox 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() { var chkArray = []; $(".chk:checked").each(function() { chkArray.push($(this).val()); }); /* check if there is selected checkboxes, by default the length is 1 as it contains one single comma */ if(chkArray.length > 1){ alert("You have selected " + chkArray); }else{ alert("Please at least one of the checkbox"); } } function getValueUsingParentTag(){ var chkArray = []; /*This will check all checkboxes that have a parent id named 'checkboxlist' attached to it and checks if it is checked. */ $("#checkboxlist input:checked").each(function() { chkArray.push($(this).val()); }); /* Check if there is atleast one selected checkboxes, by default the length is 1 as it contains one single comma */ if(chkArray.length > 1){ alert("You have selected " + chkArray); }else{ alert("Please at least one of the checkbox"); } } |