Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

jQuery get selected checkbox text

Suggested Videos
Part 10 - jQuery input vs :input
Part 11 - jQuery checked selector
Part 12 - Select values of checkbox group with jquery



In this video we will discuss how to get the checked checkbox text along with the value. This is continuation to Part 12, please watch Part 12 from jQuery tutorial before proceeding.



Here is what we want to do. As we check the checkboxes, we want to display the count of checkboxes checked and their text and values.
jQuery get checkbox checked text

<html>
<head>
    <title></title>
    <script src="jquery-1.11.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('input[name="skills"]').click(function () {
                getSelectedCheckBoxes('skills');
            });

            $('input[name="cities"]').click(function () {
                getSelectedCheckBoxes('cities');
            });

            var getSelectedCheckBoxes = function (groupName) {
                var result = $('input[name="' + groupName + '"]:checked');
                if (result.length > 0) {
                    var resultString = result.length + " checkbox checked<br/>";
                    result.each(function () {
                        var selectedValue = $(this).val();
                        resultString += selectedValue + " - "
                            + $('label[for="option-' + selectedValue + '"]').text() + "<br/>";
                    });
                    $('#div' + groupName).html(resultString);
                }
                else {
                    $('#div' + groupName).html("No checkbox checked");
                }
            };
        });
    </script>
</head>
<body style="font-family:Arial">
    Skills :
    <input type="checkbox" name="skills" value="js" />
    <label for="option-js">JavaScript</label>
    <input type="checkbox" name="skills" value="jq" />
    <label for="option-jq">jQuery</label>
    <input type="checkbox" name="skills" value="cs" />
    <label for="option-cs">C#</label>
    <input type="checkbox" name="skills" value="vb" />
    <label for="option-vb">VB</label>
    <br /><br />
    Preferred Cities :
    <input type="checkbox" name="cities" value="ny" />
    <label for="option-ny">New York</label>
    <input type="checkbox" name="cities" value="nd" />
    <label for="option-nd">New Delhi</label>
    <input type="checkbox" name="cities" value="ln" />
    <label for="option-ln">London</label>
    <br /><br />
    Selected Skills:<br />
    <div id="divskills"></div>
    <br />
    Selected Cities:<br />
    <div id="divcities"></div>
</body>
</html>

jQuery tutorial for beginners

No comments:

Post a Comment

It would be great if you can help share these free resources