jQuery

How to get the values and text of selected checkboxes using jQuery

In this article we will learn How to get the values and text of selected checkboxes using jQuery.

In this blog we will discuss How to get the checked checkbox text along with value.
how-to-get-the-values-and-text-of-selected-checkboxes-using-jquery
Html
The following HTML Markup consists of an HTML input checkbox, label and div.

<body>
    Hobbies:
    <input type="checkbox" name="hobbies" value="cricket" />
    <label for="cb-cricket">Cricket</label>
    <input type="checkbox" name="hobbies" value="swimming" />
    <label for="cb-swimming">Swimming</label>
    <input type="checkbox" name="hobbies" value="blog" />
    <label for="cb-blog">Blog</label>
    <input type="checkbox" name="hobbies" value="coding" />
    <label for="cb-coding">Coding</label>
    <br /><br />
    Selected Hobbies:<br />
    <div id="divhobbies"></div>
</body>

Key Point :Add this library link :

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

jQuery Code
write this jQuery code for How to get the values and text of selected checkboxes using jQuery ?
You can see here perform click event handler when user check checkboxes and call a function getSelectedCheckBoxwithValueText() with one parameter.Pass here group name as parameter.
you can see in HTML Group Name is “hobbies”.
Use here jQuery :checked selector in combination with the each method to retrieve the values of all checkboxes selected in a group.
each() : The each() method used here iterates over all the checkboxes that are checked.

<script>
        $(document).ready(function () {
            $('input[type="checkbox"]').click(function () {
                getSelectedCheckBoxwithValueText("hobbies")               
            });
            var getSelectedCheckBoxwithValueText = function (name1) {
                var data = $('input[name="' + name1 + '"]:checked');
                if (data.length > 0) {
                    var resultdata='' ;
                    data.each(function () {
                        var selectedValue = $(this).val();
                        resultdata += selectedValue + " - "
                            + $('label[for="cb-' + selectedValue + '"]').text() + "<br/>";

                    });
                    $("#divhobbies").html(resultdata);
                }
                else {
                    $("#divhobbies").html("No Check box selected");
                }
               

            };
        });
    </script>

Leave a Reply

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