7

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

 2 years ago
source link: https://www.laravelcode.com/post/how-to-get-the-values-of-selected-checkboxes-in-a-group-using-jquery
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

  7358 views

  1 year ago

jQuery

Ad byValueimpression

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-1.12.4.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>
Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]

Related Articles

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK