There are two ways in JavaScript to check the marked radio button or to identify which radio button is selected.. They can be checked once they are created or specified in HTML form.
JavaScript offers two DOM methods for this: 1. getElementById 2. querySelector
The input radio checked property is used to check whether the checkbox is selected or not. Use document.getElementById(‘id’).checked method for this. It will return the checked status of the radio button as a Boolean value. It can be either true or false.
True – If radio button is selected.
False – If radio button is not selected/ checked.
For Eg: (1. getElementById ) : Suppose we have a radio button named Summer and id = ‘summer’. Now, we will check using this button id that the radio button is marked or not.
if(document.getElementById('summer').checked == true) {
document.write("Summer radio button is selected");
} else {
document.write("Summer radio button is not selected");
}
(2. querySelector()) : Suppose we have a group of radio buttons having the name property name = ‘season’ for all buttons. Now, between these buttons named season we will check which one is selected.
var getSelectedValue = document.querySelector( 'input[name="season"]:checked');
if(getSelectedValue != null) {
document.write("Radio button is selected");
else {
document.write("Nothing has been selected");