September 7, 2021
How to Get Checkbox Value in Javascript
In this tutorial, you will learn how to get checkbox value in javascript. If you are having checkboxes in your HTML file, then it is obvious you want to get the value of the selected checkbox and do something with it.
I am assuming that you are only going to select one checkbox and get its value using javascript. Getting values of multiple selected checkboxes is out of the scope of this tutorial.
In the following example, we have multiple checkboxes. I will select one checkbox randomly and upon click of a button, I will display its value or label text on the screen. Please have a look over the code example and steps given below.
HTML & CSS
- We have a few elements in the HTML file and that includes
div
,label
,button
, andh1
. - The
div
element is just a wrapper for the rest of the elements. - We have created multiple checkboxes using
input
element. - The inner text for the
button
element is“Show”
and for theh1
element is“Result”
. - 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> <label><input type="checkbox" value="orange">Orange</label> <label><input type="checkbox" value="apple">Apple</label> <label><input type="checkbox" value="mango">Mango</label> <label><input type="checkbox" value="kiwi">Kiwi</label> <button>Show</button> <h1>Result</h1> </div> <script src="script.js"></script> </body> </html>
body { text-align: center; } div{ display: inline-block; } button { display: block; margin: 20px auto; }
Javascript
- We have selected
button
element andh1
element usingdocument.querySelector()
and stored them inbtnShow
andresult
variables respectively. - We have attached the
click
event to thebutton
element. - We are using CSS selector
input[type="checkbox"]:checked
to get selected checkbox and storing it incheckbox
variable. - As you can see each
input
element is wrapped with alabel
element. That means thelabel
element is the parent of theinput
element. In javascript, each element hasparentElement
property which we can use to get the parent element. Similarly, we can get text content using thetextContent
property. We are using both of them to get the label text of the selected checkbox. - You can also get the value of the selected checkbox by using the
value
property.
let btnShow = document.querySelector('button'); let result = document.querySelector('h1'); btnShow.addEventListener('click', () => { let checkbox = document.querySelector('input[type="checkbox"]:checked'); result.innerText = checkbox.parentElement.textContent; });