Search code examples
javascripthtmlradio-button

How to get the value of a selected radio button


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 JavaScript code:

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.


Solution

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

    The rates element is a div, so it won't have a value. This is probably where the undefined is coming from.

    The checked property will tell you whether the element is selected:

    if (document.getElementById('r1').checked) {
      rate_value = document.getElementById('r1').value;
    }
    

    Or

    $("input[type='radio'][name='rate']:checked").val();