Get/Set Multiple Checkbox Values Using jQuery

In this article, we will learn how we can set and get multiple checkboxes values using jQuery.

 

Prerequisites:

  • Basic knowledge of JavaScript

You can use the following code for performing the functionality.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-sm-1 ">
                <label class="control-label">Hobbies </label>
            </div>
            <div class="col-sm-6 col-md-3">
                <div class="form-check">
                    <input type="checkbox" id="chk1" class="form-check-input" value="Games" />&nbsp;Games &nbsp;
                    &nbsp; &nbsp;
                    <input type="checkbox" id="chk2" class="form-check-input" value="Reading" />&nbsp;Reading &nbsp;
                    &nbsp; &nbsp;
                    <input type="checkbox" id="chk3" class="form-check-input" value="Music" /> &nbsp;Music &nbsp;
                    &nbsp;
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-sm-2 ">
                <button type="button" class="btn btn-primary" id="btnSet" value="SET">SET</button>
            </div>
            <div class="col-sm-2 ">
                <button type="button" class="btn btn-info" id="btnGet" value="GET">GET</button>
            </div>
        </div>
    </div>
</body>

<script>
    $(document).ready(function () {
        var setCheckBoxValue = '';
        $(document).on("click", "#btnSet", function () {
            var hobbiesData = ["Games","Music"]
            $('.form-check-input[type="checkbox"]').map(function () { 
                hobbiesData.includes($(this).val()) ? $(this).prop('checked', true) : $(this).prop('checked', false) 
            });
        });

        $(document).on("click", "#btnGet", function () {
            setCheckBoxValue = $('.form-check-input[type="checkbox"]:checked').map(function () {
                return $(this).val()
            }).get().join(',');
            alert(setCheckBoxValue);
        });
    });
</script>
</html>

OUTPUT

I hope you guys understand how we can do that.

Let me know if you face any difficulties.

Submit a Comment

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

Subscribe

Select Categories