Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

javascript - 如何获得所选单选按钮的价值?(How to get value of selected radio button?)

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

(我想从一组单选按钮中获取选定的值。)

Here's my HTML:

(这是我的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:

(这是我的.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.

(我一直不确定。)

  ask by ZombieBatman translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

在IE9及更高版本以及所有其他浏览器中都可以使用。

document.querySelector('input[name="rate"]:checked').value;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...