Open In App

How to get all checked values of checkbox in JavaScript ?

Last Updated : 03 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

A checkbox is a selection box that enables users to pick true or false in a binary manner by checking or unchecking it. When a checkbox is checked, it shows that the value has been chosen by the user, and when a checkbox is not checked indicates false which denotes that the user has not chosen the value. In this article, we will discuss how we can get all the checked values from the selected checkbox using HTML and javascript.

Syntax:

<input type="checkbox" id="" value="on" name="">

Approach

  • create an HTML document with a green-themed header (“GeeksforGeeks”).
  • Add Checkboxes for HP, DELL, MAC, and ASUS laptops with the same name (“laptop”).
  • The header color is set to green using inline CSS.
  • Checkboxes allow users to select multiple laptop brands.
  • getValue() function triggered by a button click.
  • Iterates through checkboxes build a result string of selected values.
  • The result is displayed dynamically using document.write() a paragraph (“<p>”) tag.

Example: In this example, we will create four checkboxes but with the requirement that the user checks only two checkboxes between them, then we will fetch the value of marked checkboxes.

HTML




<!DOCTYPE html>
<html lang="en">
 
<body>
    <h1 style="color: green;">
        GeeksforGeeks
    </h1>
    <input type="checkbox"
           name="laptop"
           value="HP">HP laptop<br>
    <input type="checkbox"
           name="laptop"
           value="DELL">DELL laptop<br>
    <input type="checkbox"
           name="laptop"
           value="MAC">MAC laptop<br>
    <input type="checkbox"
           name="laptop"
           value="ASUS">ASUS laptop<br>
    <button onclick="getValue()">
        Get Value
    </button>
    <script>
        function getValue() {
            let checkboxes =
                document.getElementsByName('laptop');
            let result = "";
            for (var i = 0; i < checkboxes.length; i++) {
                if (checkboxes[i].checked) {
                    result += checkboxes[i].value
                        + " " + " Laptop, ";
                }
            }
            document.write("<p> You have selected : "
                + result + "</p>");
        }
    </script>
</body>
 
</html>


Output: 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads