Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (20.3k points)

I want to get the selected value from a group of radio buttons.

Here's my HTML:

<div id="rates">

  <input type="radio" id="r1" name="rate" value="Fixed Rate"> Fixed Rate

  <input type="radio" id="r2" name="rate" value="Variable Rate"> Variable Rate

  <input type="radio" id="r3" name="rate" value="Multi Rate" checked="checked"> Multi Rate  

</div>

Here's my .js:

var rates = document.getElementById('rates').value;

var rate_value;

if(rates =='Fixed Rate'){

    rate_value = document.getElementById('r1').value;

}else if(rates =='Variable Rate'){

    rate_value = document.getElementById('r2').value;

}else if(rates =='Multi Rate'){

    rate_value = document.getElementById('r3').value;

}  

document.getElementById('results').innerHTML = rate_value;

I keep getting undefined.

1 Answer

0 votes
by (40.7k points)

You can try using the code given below:

var rates = document.getElementById('rates').value;

In the above code, rates element is a div, hence it will not have a value. This is where the undefined is coming from.

Along with that, you can use checked property, it will tell you whether the element is selected or not:

if (document.getElementById('r1').checked) {

  rate_value = document.getElementById('r1').value;

}

Browse Categories

...