How to check if Checkbox is Checked or not using Plain JavaScript

How to check if Checkbox is Checked or not using Plain JavaScript

<em style="color: rgb(108, 131, 154);">You can use plain JavaScript methods to check if a checkbox or multiple checkboxes on a webpage are checked or not. There’s no need to use any library like jQuery etc. for this purpose. In-fact the method that I am showing you here can also be used on dynamically created checkboxes.</em>

You can use plain JavaScript methods to check if a checkbox or multiple checkboxes on a webpage are checked or not. There’s no need to use any library like jQuery etc. for this purpose. In-fact the method that I am showing you here can also be used on dynamically created checkboxes.

Example 1

In the first example, I am using checkboxes that I have added at design time. The checkboxes are inside a <div> element that serves as a container. With a simple script, I’ll check if a checkbox is checked or not.

<!DOCTYPE html>
<html>
<body>
    <p>Select one or more checkboxes and click the button!</p>

&lt;div id="birds"&gt;
    &lt;input type="checkbox" id="brd1" value="Mourning Dove" /&gt;
    &lt;label for="brd1"&gt;Mourning Dove&lt;/label&gt;
    &lt;br /&gt;
    &lt;input type="checkbox" id="brd2" value="Rock Pigeon" /&gt;
    &lt;label for="brd2"&gt;Rock Pigeon&lt;/label&gt;
    &lt;br /&gt;
    &lt;input type="checkbox" id="brd3" value="Black Vulture" /&gt;
    &lt;label for="brd3"&gt;Black Vulture&lt;/label&gt;
&lt;/div&gt;
&lt;p&gt;
    &lt;input type="button" id="check" onclick="nowCheck()" value="Click it" /&gt;
&lt;/p&gt;

</body> <script> function nowCheck() { // Get all the child elements inside the DIV. var cont = document.getElementById('birds').children;

    for (var i = 0; i &lt; cont.length; i++) {
        // Check if the element is a checkbox.
        if (cont[i].tagName == 'INPUT' &amp;&amp; cont[i].type == 'checkbox') {
            // Finally, check if the checkbox is checked.
            if (cont[i].checked) {
                alert(cont[i].value + ' is checked!');
            }
        }
    }
}

</script> </html>

Try it

It’s a simple script. First, I am getting all the child elements inside a <div> element and checking if any child element is a checkbox. I am running a for loop to check the type of elements that I have inside the <div>.

Next, using the .checked property, I am checking if the checkbox is checked or not.

if (cont[i].checked) { }

The property .checked returns a Boolean value (true or false). So, if a checkbox is checked, the property returns true, or else its false.

Example 2

The same above procedure (or method) can be used to check dynamically created checkboxes.

You can easily create checkboxes dynamically using JavaScript and add it to a webpage. These checkboxes too need to be checked, in some cases.

Here’s how you can do this.

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    Enter a Value <input type="text" id="birds" autofocus />
    <input type="button" id="bt" value="Create Checkbox" onclick="createChk(birds)" />
    <p id="container"></p>

&lt;p&gt;
    &lt;input type="button" id="check" onclick="nowCheck()" value="Click it validate!" /&gt;
&lt;/p&gt;

</body> <script> function nowCheck() { // Get all the child elements inside the container. var cont = document.getElementById('container').children;

    for (var i = 0; i &lt; cont.length; i++) {
        // Check if the element is a checkbox.
        if (cont[i].tagName == 'INPUT' &amp;&amp; cont[i].type == 'checkbox') {     
            // Finally, check if the checkbox is checked.
            if (cont[i].checked) {      
                alert(cont[i].value + ' is checked!');
            }
        }
    }
}

// Create and add checkboxes to your webpage.
var i = 1;
function createChk(obj) {
    if (obj.value !== '') {

        var chk = document.createElement('input');
        chk.setAttribute('type', 'checkbox');       // Type of element.
        chk.setAttribute('id', 'birdName' + i);     // Set element id.
        chk.setAttribute('value', obj.value);

        var lbl = document.createElement('label');
        lbl.setAttribute('for', 'birdName' + i);

        // Create a text box and append it to the label.
        lbl.appendChild(document.createTextNode(obj.value));

        // Append the newly created checkbox and label to &lt;p&gt; element.
        container.appendChild(chk);
        container.appendChild(lbl);

        obj.value = '';
        document.getElementById(obj.id).focus();

        i = i + 1;
    }
}

</script> </html>

Try it



Now, you can validate your checkboxes easily at the client side using the above methods. However, never forget to validate form data at the server side also. Hope this helps


Well, that’s it. Thanks for reading.





javascript

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

The essential JavaScript concepts that you should understand

The essential JavaScript concepts that you should understand - For successful developing and to pass a work interview

Grokking Call(), Apply() and Bind() Methods in JavaScript

In this article, we will have a look at the call(), apply() and bind() methods of JavaScript. Basically these 3 methods are used to control the invocation of the function.

JavaScript Tutorial: if-else Statement in JavaScript

This JavaScript tutorial is a step by step guide on JavaScript If Else Statements. Learn how to use If Else in javascript and also JavaScript If Else Statements. if-else Statement in JavaScript. JavaScript's conditional statements: if; if-else; nested-if; if-else-if. These statements allow you to control the flow of your program's execution based upon conditions known only during run time.

How to Retrieve full Profile of LinkedIn User using Javascript

I am trying to retrieve the full profile (especially job history and educational qualifications) of a linkedin user via the Javascript (Fetch LinkedIn Data Using JavaScript)

JavaScript Tutorial 50 - Promises in JavaScript

JavaScript Tutorial 50 - Promises in JavaScript - This tutorial describes how to create and handle promises in JavaScript.