A radio button is a graphical element utilized in forms to collect input from users. It enables users to select a single option from a set of radio buttons. Typically employed in graphical user interface (GUI) forms, radio buttons are primarily designed for making a single selection among various choices.
It is possible to select only a single radio button from a group of two or more radio buttons. In this section, we will provide you with instructions on how to select a radio button utilizing the JavaScript programming language.
To achieve this, we will initially create a form that includes radio buttons using HTML. Following that, we will implement JavaScript to validate the selected radio button. Additionally, we will determine which radio button value has been chosen by the user.
Create a radio button
Below is a straightforward example of how to generate a set of radio buttons.
Copy Code
<p> Choose your favroite season: </p>
<input type="radio" name="JTP" id="summer" value="summer">Summer<br>
<input type="radio" name="JTP" id="winter" value="winter">Winter<br>
<input type="radio" name="JTP" id="rainy" value="rainy">Rainy<br>
<input type="radio" name="JTP" id="autumn" value="autumn">Autumn<br>
Check a radio button
There is no requirement to implement any particular code to activate the radio button. They can be selected either at the time of their creation or as defined within the HTML form.
Nevertheless, we must create the JavaScript code necessary to retrieve the value of the selected radio button, which will be discussed in the following chapter:
Check the radio button is selected or not
In JavaScript, there are two methods available to determine which radio button is currently selected or to verify the checked state of a radio button. The Document Object Model (DOM) provides two approaches for this purpose.
- getElementById
- querySelector
The property that indicates whether the radio button is selected is known as the checked property. You can utilize the document.getElementById('id').checked method to determine this status. This method will yield the checked state of the radio button as a Boolean value, which can either be true or false.
True - If radio button is selected.
False - If radio button is not selected/ checked.
Examine the JavaScript code provided below to understand its functionality:
Example
For instance, consider a radio button labeled Summer with the identifier id = 'summer'. We will now verify whether this specific radio button is selected by checking its button id.
Copy Code
if(document.getElementById('summer').checked == true) {
document.write("Summer radio button is selected");
} else {
document.write("Summer radio button is not selected");
}
querySelector
The querySelector method is a JavaScript function that interacts with the Document Object Model (DOM). It leverages the shared name attribute of radio buttons contained within it. This method is employed as illustrated below to determine which radio button has been selected.
document.querySelector('input[name="JTP"]:checked')
Example
For instance, consider a set of radio buttons that share the same name attribute, specifically name = 'season' for each button. Now, among these radio buttons labeled as season, we will determine which one has been selected.
Copy Code
var getSelectedValue = document.querySelector( 'input[name="season"]:checked');
if(getSelectedValue != null) {
document.write("Radio button is selected");
} else {
document.write("Nothing has been selected");
}
Get the value of checked radio button:
Using getElementById
Here is the code snippet that retrieves the value of the selected radio button utilizing the getElementById function:
Copy Code
if(document.getElementById('summer').checked) {
var selectedValue = document.getElementById('summer').value;
alert("Selected Radio Button is: " + selectedValue);
}
Using querySelector
Below is the code that retrieves the value of the selected radio button utilizing the querySelector method:
Copy Code
var getSelectedValue = document.querySelector( 'input[name="season"]:checked');
if(getSelectedValue != null) {
alert("Selected radio button values is: " + getSelectedValue.value);
}
Full code to get selected radio button value
In this illustration, we will integrate all the previously discussed code to both generate and verify a radio button. Following that, we will retrieve the value associated with the radio button that has been selected.
Copy Code
<html>
<body>
<br><b> Choose your favroite season: </b><br>
<input type="radio" id="summer" value="Summer">Summer<br>
<input type="radio" id="winter" value="Winter">Winter<br>
<input type="radio" id="rainy" value="Rainy">Rainy<br>
<input type="radio" id="autumn" value="Autumn">Autumn<br><br>
<button type="button" onclick=" checkButton()"> Submit </button>
<h3 id="disp" style= "color:green"> </h3>
<h4 id="error" style= "color:red"> </h4>
</body>
<script>
function checkButton() {
if(document.getElementById('summer').checked) {
document.getElementById("disp").innerHTML
= document.getElementById("summer").value
+ " radio button is checked";
}
else if(document.getElementById('winter').checked) {
document.getElementById("disp").innerHTML
= document.getElementById("winter").value
+ " radio button is checked";
}
else if(document.getElementById('rainy').checked) {
document.getElementById("disp").innerHTML
= document.getElementById("rainy").value
+ " radio button is checked";
}
else if(document.getElementById('autumn').checked) {
document.getElementById("disp").innerHTML
= document.getElementById("autumn").value
+ " radio button is checked";
}
else {
document.getElementById("error").innerHTML
= "You have not selected any season";
}
}
</script>
</html>
Output
Upon execution of the aforementioned code, it will operate on the web and produce the output illustrated below:
Select one of the radio buttons and then click the Submit button to retrieve the chosen value.
If you opt not to select any season and proceed to click the Submit button, an error message will appear stating - You have not selected any season, as we have implemented validation for this scenario.
Get the value of selected radio button: querySelector
DOM querySelector method
The querySelector method is a JavaScript function utilized within the DOM. This method serves to retrieve the element that corresponds to the given CSS selector within the document. It is important to note that you must define the name attribute of the radio button in your HTML code.
The expression document.querySelector('input[name="JTP"]:checked') is utilized within the <script> tab to retrieve the value of the currently selected radio button from a set of radio buttons. This approach streamlines the code by allowing the value of the chosen radio button to be obtained with a concise line of code.
var selectedValue = document.querySelector('input[name="JTP"]:checked')
Examine the following code to understand its application with an HTML form:
Copy Code
<html>
<body>
<br><b> Choose your favroite season: </b><br>
<input type="radio" name="season" id="summer" value="Summer"> Summer <br>
<input type="radio" name="season" id="winter" value="Winter"> Winter <br>
<input type="radio" name="season" id="rainy" value="Rainy"> Rainy <br>
<input type="radio" name="season" id="autumn" value="Autumn"> Autumn
<br><br>
<button type="button" onclick=" checkButton()"> Submit </button>
<h3 id="disp" style= "color:green"> </h3>
<h4 id="error" style= "color:red"> </h4>
</body>
<script>
function checkButton() {
var getSelectedValue = document.querySelector(
'input[name="season"]:checked');
if(getSelectedValue != null) {
document.getElementById("disp").innerHTML
= getSelectedValue.value
+ " season is selected";
}
else {
document.getElementById("error").innerHTML
= "*You have not selected any season";
}
}
</script>
</html>
Output
Upon running the code provided above, the output will be displayed on the web as illustrated below. At this point, you can select your preferred season.
Upon selecting a value from the available radio buttons and subsequently clicking the Submit button, the chosen value will be displayed on the web page.
If you press the Submit button without selecting any of the radio buttons, an error message will appear stating - You have not selected any season.
In this context, it is evident that both getElementById('season').value and document.querySelector('input[name="JTP"]:checked') serve the same purpose. They are both utilized to retrieve the value of the selected radio button. You have the option to use either of these methods.
getElementById vs querySelector
The DOM methods getElementById and querySelector function similarly in many respects. Nevertheless, they exhibit several distinctions, including aspects such as performance and code size. Below are some of the differences between the two:
Length of code
The code that utilizes getElementById tends to be more verbose compared to that which employs querySelector. When using the getElementById method, it is necessary to examine each radio button separately to determine which one is selected.
Conversely, when utilizing the querySelector method from the Document Object Model (DOM), you are able to accomplish the task of identifying the selected radio button and retrieving its value with just a single line of code. Therefore, it can be concluded that querySelector necessitates a lesser amount of code.
Performance
Both functions deliver solid performance; however, it is essential to determine which one is superior. The getElementById method operates significantly faster compared to the querySelector method. Additionally, the querySelector method involves a certain level of complexity.
Value used by DOM methods
The getElementById function consistently employs a distinct identifier for each radio button when determining which button is selected, and it retrieves the initial element that corresponds with the specified id.
In contrast, querySelector utilizes a shared name (selector) for all radio button elements to identify the selected radio button, returning the initial element that corresponds with the given selector.