Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu January 26, 2023 › #Button #HowTo

How to get radio button value in JavaScript using class name

If you're looking for a way to get the value of radio buttons in JavaScript using class name, then in this article, I will teach you how to do that!

The first step in getting the radio button value using the class name is to find out which class is assigned by the HTML element.

Then, we can use querySelectorAll() or getElementsByClassName() methods, passing our specified class name as an argument.

let radioBtns = document.getElementsByClassName("classname"); 
    // OR 
let radioBtns = document.querySelectorAll("input[type='radio'].colors"); 
   // Get by name attribute
let radioBtns = document.querySelectorAll("input[type='radio'][name='colors']");

Now, if we console the variable colors, we may see a NodeList that represents all the radios items. We'll use Array's prototype forEach() method :

radioBtns.forEach(function(e){
    if(e.checked){
      console.log("Radio Button Value Is:" + e.value);
    }
  });  

It will iterate over each of the previously found nodes and check if their checked property returns true or false. If this is true, it means the user has already made his selection and now we just need to return its respective value using the "value" attribute.

save
listen
AI Answer
Write Your Answer
loading
back
View All