Many times we use checkbox in the form control and post the form using jquery ajax and then we are required to access those form data from client side scripts, like Javascript. Among all possible form controls, dropdown box, checkbox and radio buttons are having multiple options to select. So, we need to push all selected values of these form controls into an array using Javascript.
In this article, we have an example, for getting all selected checkbox values. With this reference, we can repeat it for other multi-valued form controls also. For that, we need to follow some simple steps listed below.
View Demo
Getting Checkbox Values in jQuery
1. Creating HTML form with checkboxes.
2. Adding jquery library file.
3. Accessing form from jQuery.
In a HTML page, create a form tag with multiple checkboxes and we should provide all checkboxes of a group with same name, to indicate that they are multiple values of the same checkbox group as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <form name="frmCheckbox" id="frmCheckbox" action="" method="post"> <table border="0" cellpadding="10" cellspacing="1" width="500" align="center"> <tr class="tableheader"> <td>Programming languages Known</td> </tr> <tr class="tablerow"> <td> <input type="checkbox" name="plang" id="plang1" value="C++" >C++<br/> <input type="checkbox" name="plang" id="plang2" value="C" >C<br/> <input type="checkbox" name="plang" id="plang3" value="Basic" >Basic<br/> <input type="checkbox" name="plang" id="plang4" value="Fortran" >Fortran<br/> <input type="checkbox" name="plang" id="plang5" value="PHP" >PHP<br/> </td> </tr> <tr class="tableheader"> <td><input id="btnSubmit" type="button" value="Submit" /></td> </tr> </table> </form> |
2.Adding jQuery Library File
It’s very common step, we need to include the path of jQuery library file before using jQuery as a source for using jQuery functions.
1 | <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script> |
3. Accessing Form from jQuery
1 2 3 4 5 6 7 8 | <script language="javascript" type="text/javascript"> $(document).ready(function () { $("#btnSubmit").click(function(){ var selectedLanguage = $('input[name="plang"]:checked').map(function(){ return this.value; }).get(); alert("The selected Programming Languages are: "+selectedLanguage); }); }); </script> |
Here we are handling button click event in document ready and mapping all the checkboxes which have been checked with using jQuery map()
utility which translate all items in an array or object to new array of items. In this map utitlity, we are returning their values to an array using its callback function. So now getting checkbox values in jQuery is very easy method.
View Demo