jQuery

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?





mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *