To check the value of a radio button group in JavaScript, we can use the document.querySelector
method to get the checked radio button.
Then we get the value
property of that to get the value of the value
attribute of the selected radio button.
For instance, if we have the following HTML:
<div>
<input type="radio" id="genderm" name="gender" value="male" />
<label for="genderm">Male</label>
<input type="radio" id="genderf" name="gender" value="female" checked />
<label for="genderf">Female</label>
</div>
Then we can get the value of the radio button with the checked
attribute by writing:
const {
value
} = document.querySelector('input[name="gender"]:checked')
console.log(value)
We use the ‘input[name=”gender”]:checked’
selected to get the radio button with the checked
attribute enabled.
And we get the value of the value
attribute with the value
property.
Therefore, value
should be 'female'
.