I am trying to get the value from a checked radio button and eventually pass that value into other functions. Currently I am only successful when I have one radio button in my html. As soon as I add another radio button with the same name my Javascript function does not work as I intended.
Here is my Javascript:
function RadioButtonValue (form) {
if (form.elements ["radio"].checked) {
return parseInt (form.elements["radio"].value)
}else{
return 0}
}
function totalRadio (form) {
var radio = RadioButtonValue (form)
form.elements ["total"].value = radio
}
Here is my HTML:
<form>
<input type="radio" name="radio" value="1" />1
<br />
<input type="radio" name="radio" value="2"/>2
<br />
<input type="button" value="Radio Button Value" onclick="javascript:totalRadio(this.form)" />
<br />
<input type="number" name="total" />
</form>
I am looking for the simplest Javascript solution, I think using a "for loop" is the solution I need but I am not sure.
Thanks for the help in advance!
Here's a loop that will just iterate through the radio buttons in the form that's being processed so it doesn't add any other checked radio buttons.
function RadioButtonValue (form) {
var returnVal = 0;
var radios = form.elements ["radio"];
for(var r = 0; r < radios.length; r++) {
if (radios[r].checked) {
returnVal = parseInt (radios[r].value);
}
}
return returnVal;
}
function totalRadio (form) {
var radio = RadioButtonValue (form)
form.elements ["total"].value = radio
}
Here it is in a fiddle: http://jsfiddle.net/PM8Jm/1/
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments