简体   繁体   English

多个单选按钮,需要将所选值传递给javascript

[英]Multiple radio buttons, need to pass selected value to javascript

So I have a javascript to add together values entered, that works just fine. 因此,我有一个JavaScript可以将输入的值相加,效果很好。 I need to add the value of the selected radio button to this equation. 我需要将所选单选按钮的值添加到此公式中。 I was adding by Id value, so I imagine sticking to that would be great. 我是按ID值添加的,所以我想坚持下去会很棒。 I cannot figure this out...I've searched but everywhere just indicates how to validate the selection. 我无法弄清楚...我已经搜索过,但到处都只表明如何验证选择。

I don't think this is duplicated...I need the value of the selected radio button and the value has to be added to the equation. 我不认为这是重复的...我需要所选单选按钮的值,并且必须将该值添加到等式中。

Radio Options
<input type="radio" name="int" id="0" value="none">None
<input type="radio" name="int" id="10" value="Ten">10
<input type="radio" name="int" id="20" value="Twenty">20
<input type="radio" name="int" id="30" value="Thirty">30

This is what my javascript looks like: 这是我的JavaScript的样子:

function calculate()

{
var userInput = document.getElementById("pkg").value*1;
var userInput2 = document.getElementById("pep").value*1;
var addBox = document.getElementById("addtl").value*1;
var totalNum = document.getElementById("add_cost").value*1;

 // Sum everything
var SumAll = userInput + userInput2 + (addBox*totalNum);

// print the total 
document.getElementById("Sum").innerHTML = SumAll.toFixed(2)

}

Just check which of the radio buttons is "checked", like this: 只需检查哪个单选按钮被“选中”即可,如下所示:

var values = document.getElementsByName("int");

for(var i = 0; i < values.length; i++) {
   if(values[i].checked == true) {
       selectedValue = values[i].value;
   }

} }

The one that is selected will have checked == true . 选择的一个将被checked == true

See this Fiddle for an example (use the console to see the buttons being selected). 有关示例,请参见此小提琴 (使用控制台查看所选择的按钮)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM