Multiple Checkboxes can be selected by using a simple Javascript code.
Whenever user clicks on the submit button then we can loop through all the form data and we can check whether the checkbox is checked or not by using the “checked” property of checkbox.
Following is a sample code to select multiple checkbox from html page and retrieve values of multiple selected items.
We are storing all “checked” checkbox values in an array “selectedItems”. And we can print or display it. Here I am using “console.log” function of the browser, which is available in many browsers to print logs. To see “console.log” messages, right click and select “Inspect” in chrome. You can use firebug for firebox.
Lets create our simple form which will display number of checkboxes.
<p>Select Items you OWN</p> <form> <input type="checkbox" name="owns" value="Bike">Bike<br/> <input type="checkbox" name="owns" value="Car">car<br/> <input type="checkbox" name="owns" value="Refridgerator">Refridgerator<br/> <input type="checkbox" name="owns" value="Mobile">Mobile<br/> <input type="checkbox" name="owns" value="Tablet">Tablet<br/> <input type="checkbox" name="owns" value="Computer">Computer<br/> <input type="button" value="Get Values" >Javascript Function
<script type="text/javascript"> function getMultipleCheckbox(inputdata) { var selectedItems = []; var count = 0; for(var i=0;i<inputdata.length;i++) { if(inputdata[i].checked) { selectedItems[count] = inputdata[i].value; count++; } } for(var loop=0; loop< selectedItems.length; loop++) { console.log(selectedItems[loop]); } return selectedItems; } </script>Full Source Code
Copy paste below code to file and save it as a HTML file and open it to check result. Optionally you can you “alert” instead of “console.log” for printing results.
<p>Select Items you OWN</p> <form> <input type="checkbox" name="owns" value="Bike">Bike<br/> <input type="checkbox" name="owns" value="Car">car<br/> <input type="checkbox" name="owns" value="Refridgerator">Refridgerator<br/> <input type="checkbox" name="owns" value="Mobile">Mobile<br/> <input type="checkbox" name="owns" value="Tablet">Tablet<br/> <input type="checkbox" name="owns" value="Computer">Computer<br/> <input type="button" value="Get Values" >
View Comments (0)