How to Check a Checkbox Using JavaScript
In this tutorial, you will learn how to check a checkbox using javascript. A checkbox is a tiny square that you can check or uncheck. Checkboxes are used whenever you want to provide a limited number of choices to a user.
Whenever you check a checkbox, a tick symbol appears on top of it and that means whatever the statement or word is written right next to it, you are agreeing or approving that. This is generally done by clicking on the checkbox with the help of the left button on the mouse.
The input element can be of different types and one of them is the checkbox
. When the type of input element is a checkbox
, we have access to the checked
property. This property returns a Boolean value depending upon the status of the checkbox. Also, it can be used to check or uncheck the checkbox.
In the following example, we are going to check a checkbox dynamically upon button click. Please have a look over the code example and the steps given below.
HTML & CSS
- We have 4 elements in the HTML file (
div
,input
,label
, andbutton
). Thediv
element with a class ofcontainer
is just a wrapper for the rest of the elements. - The
innerText
for thebutton
element is“Check”
. - The
input
element is of typecheckbox
and it has a label of“I like Javascript”
. It is unchecked by default and we are going to check it with the help of javascript. - We have done some basic styling using CSS and added the link to our
style.css
stylesheet inside thehead
element. - We have also included our javascript file
script.js
with ascript
tag at the bottom.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="style.css"> <title>Document</title> </head> <body> <div class="container"> <button>Check</button> <div> <input type="checkbox" id="coding" value="javascript"> <label for="coding">I like Javascript</label> </div> </div> <script src="script.js"></script> </body> </html>
.container { width: 400px; margin: auto; display: flex; flex-direction: column; } button, input { padding: 5px 10px; margin-bottom: 20px; }
Javascript
- We have selected the
input
element and thebutton
element using thedocument.querySelector()
method and stored them incheckbox
andbtn
variables respectively. - We have attached the
click
event listener to thebutton
element. - In the event handler function, we are using the
checked
property of theinput
element and setting it totrue
. This will change the status of checkbox from unchecked to checked.
let checkbox = document.querySelector("input[type='checkbox']"); let btn = document.querySelector("button"); btn.addEventListener("click", () => { checkbox.checked = true });