How to get radio button value in JavaScript using class name
On - 13 Feb, 2023
By - Apu Gorai
The document.querySelector() method can be used to get the value of a radio button in JavaScript using the class name.
This method takes a CSS selector string as its argument and returns the first element that matches it.
Example -
<script>
let myRadio = document.querySelector('input[name="myRadio"]:checked');
console.log(myRadio.value);
</script>
Use the document.getElementsByClassName() method to get an array of elements that have the specified class name.
<script>
let a = document.getElementsByClassName('myR');
</script>
Loop through the array to find the checked radio button.
<script>
for (var i=0; i < a.length; i++) {
if(a[i].checked) {
console.log(a[i].value);
}
}
</script>
Use the querySelectorAll() method to get an array of all the elements that match the specified selector:
Example -
<script>
let e = document.querySelectorAll('.myRadio:checked');
for (let i=0; i < e.length; i++) {
console.log(e[i].value);
}
</script>