jQuery <input> get values from selected checkboxes group

Description

jQuery <input> get values from selected checkboxes group

View in separate window

<!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-1.12.4.min.js"></script>
<script>
    $(document).ready(function() {
        $("button").click(function(){
            var favorite = [];/*from  ww w  .  j a v  a2  s .c  om*/
            $.each($("input[name='sport']:checked"), function(){
                favorite.push($(this).val());
            });
            document.getElementById("demo").innerHTML = 
               "My favourite sports are: " + favorite.join(", ");
        });
    });
</script>
</head>
<body>
    <p id="demo"></p>
    <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>
        <hr>
        <button type="button">Get Values</button>
    </form>
</body>
</html>



PreviousNext

Related