How to get the value of a CheckBox with jQuery
In this tutorial, we are going to see how to get the value of a CheckBox with jQuery. You can simply use jQuery’s :checked selector in combination with the method each() to get the values of all selected checkboxes. The each() method used here simply to iterate through all the checkboxes. Here is an example:
HTML Code:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>How to get the value of a CheckBox</title> <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <script type="text/javascript"> // Put the jQuery code Here </script> </head> <body> <h5>What is your favorite programming language?</h5> <p> <label><input type="checkbox" name="langage" value="javascript">JavaScript</label><br> <label><input type="checkbox" name="langage" value="python">Python</label><br> <label><input type="checkbox" name="langage" value="php">PHP</label><br> <label><input type="checkbox" name="langage" value="java">Java</label><br> <label><input type="checkbox" name="langage" value="scala">Scala</label> </p> <input type="button" value="Get the value"> </body> </html>
jQuery Code:
$(document).ready(function() { $("input[type='button']").click(function() { var langPref = []; $.each($("input[name='langage']:checked"), function() { langPref.push($(this).val()); }); alert("Your preferred programming language is: " + langPref.join(", ")); }); });
Result |
---|
What is your favorite programming language?
|