Q:

How to get the values of selected checkboxes in a group using jQuery

0

How to get the values of selected checkboxes in a group using jQuery

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the jQuery :checked selector

You can use the jQuery :checked selector in combination with the each() method to retrieve the values of all checkboxes selected in a group. The each() method used here simply iterates over all the checkboxes that are checked. Let's try out an example to see how it works:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Get Values of Selected Checboxes</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
    $(document).ready(function() {
        $("button").click(function(){
            var favorite = [];
            $.each($("input[name='sport']:checked"), function(){
                favorite.push($(this).val());
            });
            alert("My favourite sports are: " + favorite.join(", "));
        });
    });
</script>
</head>
<body>
    <form>
        <h3>Select your favorite sports:</h3>
        <label><input type="checkbox" value="football" name="sport"> Football</label>
        <label><input type="checkbox" value="baseball" name="sport"> Baseball</label>
        <label><input type="checkbox" value="cricket" name="sport"> Cricket</label>
        <label><input type="checkbox" value="boxing" name="sport"> Boxing</label>
        <label><input type="checkbox" value="racing" name="sport"> Racing</label>
        <label><input type="checkbox" value="swimming" name="sport"> Swimming</label>
        <br>
        <button type="button">Get Values</button>
    </form>
</body>
</html>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to bind click event to dynamically created HTM... >>
<< How to get the value of selected radio button in a...