简体   繁体   中英

Multiple radio buttons, need to pass selected value to javascript

So I have a javascript to add together values entered, that works just fine. 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. 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:

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 .

See this Fiddle for an example (use the console to see the buttons being selected).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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