Select Values of Checkbox Group with jQuery

How to Select Values of Checkbox Group with jQuery

In this article, I am going to discuss How to Select Values of the Checkbox Group with jQuery with Examples. Please read our previous article, where we discussed jQuery Checked Selector. At the end of this article, you will understand everything about how to Select Values of Checkbox Group with jQuery. This is a continuation part to our previous article, so please read our previous article before proceeding to this article.

How to select values of checkbox group with jQuery?

In our previous article, we have learned that how to get the values of selected checkboxes. But there is a small issue. Let us have a look at the issue first and for this please have a look at the following example.

<!DOCTYPE html>
<html>
<head>
    <title>How to Select Values of Checkbox Group with jQuery</title>
</head>
<body>
    <section>
        <form action="/">
            <fieldset>
                <legend>Skillset: </legend>
                <label>HTML:
                    <input type="checkbox" name="skillset" value="HTML" /></label>
                <label>CSS:
                    <input type="checkbox" name="skillset" value="CSS"/></label>
                <label>JavaScript:
                    <input type="checkbox" name="skillset" value="JavaScript"/></label>
                <label>jquery:
                    <input type="checkbox" name="skillset" value="jquery"/></label>
            </fieldset>
            <br>
            <fieldset>
                <legend>Preferred Interview Location </legend>
                <label>Kolkata:
                    <input type="checkbox" name="location" value="Kolkata" /></label>
                <label>Bhubaneshwar:
                    <input type="checkbox" name="location" value="Bhubaneshwar"/></label>
                <label>Bangalore:
                    <input type="checkbox" name="location" value="Bangalore"/></label>
                <label>Pune:
                    <input type="checkbox"  name="location" value="Pune"/></label>
            </fieldset>
     </form>
     </section> </br>
    <button class="demo" id="skillset" value="submit">Get skillset</button>
    <button class="demo" id="location" value="submit">Get location</button>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
           $('#skillset').click(function () {
             var valueStore = [];
             $.each($("input[type='checkbox']:checked"), function () {
                valueStore.push($(this).val());
             });
             alert("My favourites are: " + valueStore.join(", "));
          });

          $('#location').click(function () {
             var valueStore = [];
             $.each($("input[type='checkbox']:checked"), function () {
                valueStore.push($(this).val());
             });
             alert("My favourites are: " + valueStore.join(", "));
         });
    });
    </script>
</body>
</html>

Once you run the above HTML code, you will get the following output. As you can see in the below image, here, we have two groups of checkboxes.

How to Select Values of Checkbox Group with jQuery

What our requirement is, when we click on the corresponding button, then we should get the corresponding checked value of the checkbox groups. But if we apply the event handler on both the buttons as we have done in our previous example, then we are getting the result as follows whether we click on the Get Skillset and Get Location button.

Select Values of Checkbox Group with jQuery

But we don’t want that. We want that if we click on the ‘Get skillset’ button then only we should get the values of the Skillset group and the same with the Location group. Now let’s see how to achieve that functionality?

Approach1:

We are facing that problem because we are using the type attribute to the input element. So, they are targeting all checkboxes. But what if we use the name attribute. The name attribute is different for the different groups of checkboxes. That will solve our problem. So, modify the script section of the previous example as follows.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        $('#skillset').click(function () {
            var valueStore = [];
            $.each($("input[name='skillset']:checked"), function () {
                valueStore.push($(this).val());
            });
            alert("My favourite skillset are: " + valueStore.join(", "));
        });
        $('#location').click(function () {
            var valueStore = [];
            $.each($("input[name='location']:checked"), function () {
                valueStore.push($(this).val());
            });
            alert("My favourites location are: " + valueStore.join(", "));
        });
    });
</script>

In the above code, By $(‘input[name=”skillset”]:checked’) we are targeting that group of checkbox named skillset. And the same we are doing with the group of checkbox named location by $(‘input[name=”location”]:checked’). With the above script section in place, now click on the Get Skillset button, you will only get Skill Set checked check box values as shown in the below image.

How to Select Values of the Checkbox Group with jQuery with Examples

Then click on the Get location button, you will get only the location-selected checkboxes values as shown in the below image.

How to Select Values of the Checkbox Group with jQuery

Our desired functionality is done.

Approach2:

But there is another problem with the first approach. We are creating different handlers for different buttons. What if there are many checkbox groups in our form? Will we create a different handler to get the values of every checkbox group?

No instead of this we can create a function and pass a parameter to that function. That parameter will dynamically change the value of the name attribute and we will invoke that function by just using two different parameters. To do so, please modify the script section of your code as follows.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
  $(document).ready(function() {
    $('#skillset').click(function() {
      getCheckedValues('skillset');
    });
    $('#location').click(function() {
      getCheckedValues('location');
    });
  });

  function getCheckedValues(nameAttr) {
    var valueStore = [];
    $.each($("input[name='" + nameAttr + "']:checked"), function() {
      valueStore.push($(this).val());
    });
    alert("My favourites " + nameAttr + " are: " + valueStore.join(", "));
  }
</script>

With the above changes in place, now click on the Get Skillset button, you will only get selected Skill Set check box values as shown in the below image.

How to Select Values of Checkbox Group with jQuery

Then click on the Get location button, you will get only the selected location check box values as shown in the below image.

How to Select Values of the Checkbox Group with jQuery with Examples

Thus, our functionality is achieved with a minimal piece of code. Following is the complete code of the above example.

<!DOCTYPE html>
<html>
<head>
    <title>How to Select Values of Checkbox Group with jQuery</title>
</head>
<body>
    <section>
        <form action="/">
            <fieldset>
                <legend>Skillset: </legend>
                <label>HTML:
                    <input type="checkbox" name="skillset" value="HTML" /></label>
                <label>CSS:
                    <input type="checkbox" name="skillset" value="CSS"/></label>
                <label>JavaScript:
                    <input type="checkbox" name="skillset" value="JavaScript"/></label>
                <label>jquery:
                    <input type="checkbox" name="skillset" value="jquery"/></label>
            </fieldset>
            <br>
            <fieldset>
                <legend>Preferred Interview Location </legend>
                <label>Kolkata:
                    <input type="checkbox" name="location" value="Kolkata" /></label>
                <label>Bhubaneshwar:
                    <input type="checkbox" name="location" value="Bhubaneshwar"/></label>
                <label>Bangalore:
                    <input type="checkbox" name="location" value="Bangalore"/></label>
                <label>Pune:
                    <input type="checkbox"  name="location" value="Pune"/></label>
            </fieldset>
     </form>
     </section> </br>
    <button class="demo" id="skillset" value="submit">Get skillset</button>
    <button class="demo" id="location" value="submit">Get location</button>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
      $(document).ready(function() {
        $('#skillset').click(function() {
          getCheckedValues('skillset');
        });
        $('#location').click(function() {
          getCheckedValues('location');
        });
      });

      function getCheckedValues(nameAttr) {
        var valueStore = [];
        $.each($("input[name='" + nameAttr + "']:checked"), function() {
          valueStore.push($(this).val());
        });
        alert("My favourites " + nameAttr + " are: " + valueStore.join(", "));
      }
    </script>
</body>
</html>

In the next article, we will discuss how to get the checked checkbox text along with the value in jQuery with Examples. Here, in this article, I try to explain How to Select Values of Checkbox Group with jQuery with Examples and I hope you enjoy this Select Values of the Checkbox Group with the jQuery article.

1 thought on “Select Values of Checkbox Group with jQuery”

Leave a Reply

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