How to Check a Radio Button Using JavaScript
In this tutorial, you will learn how to check a radio button using javascript. A radio button is a tiny circle that you can check or uncheck. Radio buttons are used whenever you want to provide a limited number of choices to a user, but he can only select one of them.
Whenever you check a radio button, a dot symbol appears in its center 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 radio button with the help of the left button on the mouse.
The input element can be of different types and one of them is the radio
. When the type of input element is radio, we have access to the checked
property. This property returns a Boolean value depending upon the status of the radio button. Also, it can be used to check or uncheck the radio button.
In the following example, we are going to check a radio button 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 Radio”
. - The
input
element is of typeradio
and it has a label of“I like Python”
. 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 Radio</button> <div> <input type="radio" id="python" value="python"> <label for="python">I like Python</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 inradioBtn
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 radio button from unchecked to checked.
let radioBtn = document.querySelector("#python"); let btn = document.querySelector("button"); btn.addEventListener("click", () => { radioBtn.checked = true });