How to Get Multiple Checkbox Value in jQuery Using Array

Some geeks still do not know about How to get multiple checkbox value in jQuery using array. In this article, we will learn to get multiple checkbox values in jQuery using an array.

Get Multiple Checkbox Value in 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 Multiple 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.

Read Also: How to Set Selected Value of Dropdown in JavaScript

Conclusion

I hope now you can easily get multiple checkbox values using jQuery query selector. Please comment your thoughts below if the above article helps you.

Enjoy Scripting πŸ™‚

 

2 thoughts on “How to Get Multiple Checkbox Value in jQuery Using Array

  1. How to get the multiple checkbox value based on selected , the above code will gives the result in sequnce order based on the input which is at 1st positon . How to get the values based on what order i checked

    1. Actually, there is no direct solution to get values based on what order you checked. You should try storing a sequence of click events on checkboxes by id and use it to fulfill your purposes.

Leave a Reply

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