How to Get All the Selected Checkbox Values Onclick Using jQuery

Checkboxes are quite useful in web forms. Even more, jQuery provides a handy functionality to manage checkboxes.

Here, we are going to learn how to get the values of selected checkboxes with a similar group.

Get Checkbox Values Onclick Event Using jQuery

We can use :checked selector in jQuery to select only selected values.

Example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Get All the Selected Checkbox Value in jQuery</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
</head>
<body>
    <form>
        <h3>Select your favorite programming languages:</h3>
        <label><input type="checkbox" value="Java" name="language"> Java</label>
        <label><input type="checkbox" value="PHP" name="language"> PHP</label>
        <label><input type="checkbox" value="JavaScript" name="language"> JavaScript</label>
        <label><input type="checkbox" value="jQuery" name="language"> jQuery</label>
        <label><input type="checkbox" value="React" name="language"> React</label>
        <br>
        <button type="button">Get Selected Values</button>
    </form>
  <script>
      $(document).ready(function() {
          $("button").click(function(){
              var arr = [];
              $.each($("input[name='language']:checked"), function(){
                  arr.push($(this).val());
              });
              alert("Your favourite programming languages are: " + arr.join(", "));
          });
      });
  </script>
</body>
</html>

Explanation

In the above code, we created a group of checkboxes and a button to trigger the function. Using jQuery we first set an onclick event on the button after the document is loaded.

In the onclick event, we created a function in which we first declared an array named arr. After that, we used a query selector to select all the selected checkboxes. Finally, we print all the vales in an alert box.

Conclusion

I hope now you can easily get all the values of checked checkboxes using jQuery query selector. Please comment your thoughts below if the above article helps you.

Enjoy Scripting 🙂

 

Leave a Reply

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

Read previous post:
Disable Input Fields Using JavaScript
How to Onclick Disable Input Field JavaScript

Sometimes, we need to prevent users to fill the input fields. To do that we have to disable input fields...

Close