How to get Selected Checkbox Text in jQuery

How to get Selected Checkbox Text in jQuery with Examples

In this article, I am going to discuss How to get Selected Checkbox Text and Value in jQuery with Examples. Please read our previous article, where we discussed How to Select Values of Checkbox Group with jQuery. At the end of this article, you will understand everything about How to get Selected Checkbox Text in jQuery.

How to Get Selected Checkbox Text in jQuery?

In the previous article, we have learned to extract the values of different checkbox groups. In the examples of the previous article notice one thing, our value of the checkbox and the label text was the same. But what if they were different? How to extract the checkbox label texts? In this article, we will discuss that with Examples.

Example:

Let’s quickly build the HTML.

<!DOCTYPE html>
<html>
<head>
    <title>How to get Selected Checkbox Text and Value in jQuery</title>
</head>
<body>
    <section>
        <form action="/">
            <fieldset>
                <legend>Skillset: </legend>
                <label for="HTML">HTML5</label>
                <input type="checkbox" name="skillset" value="HTML" />
                <label for="CSS">CSS3</label>
                <input type="checkbox" name="skillset" value="CSS" />
                <label for="JavaScript">JS</label>
                <input type="checkbox" name="skillset" value="JavaScript" />
                <label for="jquery">jquery3.6</label>
                <input type="checkbox" name="skillset" value="jquery" />
            </fieldset>
            <br>
            <fieldset>
                <legend>Preferred Interview Location </legend>
                <label for="Kolkata">KOL</label>
                <input type="checkbox" name="location" value="Kolkata" />
                <label for="Bhubaneshwar">BBS</label>
                <input type="checkbox" name="location" value="Bhubaneshwar" />
                <label for="Bangalore">BLR</label>
                <input type="checkbox" name="location" value="Bangalore" />
                <label for="Pune">PUN</label>
                <input type="checkbox" name="location" value="Pune" />
            </fieldset>
        </form>
    </section>
    </br>
    <button class="demo" id="skillset" value="submit">Get skillset</button>
    <button class="demo" id="location" value="submit">Get location</button>
</body>
</html>

Now, if you run the above HTML, then you will get the following output in the browser.

How to get Selected Checkbox Text and Value in jQuery

Approach1

Notice that our checkbox value and checkbox label text are different here. Our objective is to get the label text. What can we do about that? In the below script, we are targeting the label element and who’s for attribute value is the ‘value’ of the checkbox fields. And we are printing our results in the console.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        $('#skillset').click(function () {
            const CheckboxChecked = $('input[name="skillset"]:checked').length;
            console.log(`Total ${CheckboxChecked} checkboxes are checked`);
            $('input[name="skillset"]:checked').each(function () {
                let value = $(this).val();
                let checkboxText = $(`label[for="${value}"]`).text();
                console.log(`Checkbox value is ${value}`);
                console.log(`Check box text is ${checkboxText}`);

            })
        });
        $('#location').click(function () {
            const CheckboxChecked = $('input[name="location"]:checked').length;
            console.log(`Total ${CheckboxChecked} checkboxes are checked`);
            $('input[name="location"]:checked').each(function () {
                let value = $(this).val();
                let checkboxText = $(`label[for="${value}"]`).text();
                console.log(`Checkbox value is ${value}`);
                console.log(`Check box text is ${checkboxText}`);
            })
        });
    });
</script>

Run the code, open the browser developer’s tool by pressing the F12 key and then select the following checkboxes and click on the Get Skillset button and please have a look at the browser console window as shown in the below image.

How to get Selected Checkbox Text in jQuery with Examples

As you can see in the above image, it prints the Skillset text and values in the console. Now, refresh the page, select the checkboxes and click on the Get location button as shown in the below image. And this time you will see the location text and values in the console.

How to Get Selected Checkbox Text in jQuery?

Following is the complete code.

<!DOCTYPE html>
<html>
<head>
    <title>How to get Selected Checkbox Text and Value in jQuery</title>
</head>
<body>
    <section>
        <form action="/">
            <fieldset>
                <legend>Skillset: </legend>
                <label for="HTML">HTML5</label>
                <input type="checkbox" name="skillset" value="HTML" />
                <label for="CSS">CSS3</label>
                <input type="checkbox" name="skillset" value="CSS" />
                <label for="JavaScript">JS</label>
                <input type="checkbox" name="skillset" value="JavaScript" />
                <label for="jquery">jquery3.6</label>
                <input type="checkbox" name="skillset" value="jquery" />
            </fieldset>
            <br>
            <fieldset>
                <legend>Preferred Interview Location </legend>
                <label for="Kolkata">KOL</label>
                <input type="checkbox" name="location" value="Kolkata" />
                <label for="Bhubaneshwar">BBS</label>
                <input type="checkbox" name="location" value="Bhubaneshwar" />
                <label for="Bangalore">BLR</label>
                <input type="checkbox" name="location" value="Bangalore" />
                <label for="Pune">PUN</label>
                <input type="checkbox" name="location" value="Pune" />
            </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 () {
                const CheckboxChecked = $('input[name="skillset"]:checked').length;
                console.log(`Total ${CheckboxChecked} checkboxes are checked`);
                $('input[name="skillset"]:checked').each(function () {
                    let value = $(this).val();
                    let checkboxText = $(`label[for="${value}"]`).text();
                    console.log(`Checkbox value is ${value}`);
                    console.log(`Check box text is ${checkboxText}`);
                })
            });
            $('#location').click(function () {
                const CheckboxChecked = $('input[name="location"]:checked').length;
                console.log(`Total ${CheckboxChecked} checkboxes are checked`);
                $('input[name="location"]:checked').each(function () {
                    let value = $(this).val();
                    let checkboxText = $(`label[for="${value}"]`).text();
                    console.log(`Checkbox value is ${value}`);
                    console.log(`Check box text is ${checkboxText}`);
                })
            });
        });
    </script>
</body>
</html>
Approach2:

Notice that our program is working fine. But there is again the same problem as the previous article. 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 as in the previous article. That parameter will dynamically change the value of the name attribute and we will invoke that function by just using two different parameters. The following jQuery code exactly does the same.

<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) {
            const CheckboxChecked = $("input[name='" + nameAttr + "']:checked").length;
            console.log(`Total ${CheckboxChecked} checkboxes are checked`);
            $.each($("input[name='" + nameAttr + "']:checked"), function () {
                let value = $(this).val();
                let checkboxText = $(`label[for="${value}"]`).text();
                console.log(`Checkbox value is ${value}`);
                console.log(`Check box text is ${checkboxText}`);
            });
        }
    });
</script>

With the above changes, we will achieve the desired output but the length of our code is minimal.

In the next article, I am going to discuss jQuery Selected Selector with Examples. Here, in this article, I try to explain How to get Selected Checkbox Text and Value in jQuery with Examples and I hope you enjoy this How to get Selected Checkbox Text and Value in the jQuery article.

Leave a Reply

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