Can't assign radio button selection to variable. Why?
The form link to below performs a bit of basic calculation, adding up a total based on selections from drop-down menus.
That portion of the form works fine. But I also need to multiply the total based on a selected value from three radio buttons.
I thought I could find a simple script online to assign the selected radio value to a variable, then multiply the total from the drop down menus by that variable.
But for some reason, something in the code is preventing me from getting the radio button value and assigning it to a variable. I'm a total noob to JS and I just can't determine the problem.
One thing I noticed is that you've used an onClick handler in the html for the radio buttons. I didn't have that in my script. Here's the code I was using to try to assign the radio value to a variable:
Code:
function process(){
var radio = "";
for (i = 0; i < 3; i++){
if (document.form_20443524032.dep[i].checked == true){
radio = document.form_20443524032.dep[i].value; }
}
}
No, the onclick event is not useful. It was only an example, I take it in w3cScholls.com.
Your code would be better with a document.form_20443524032.dep.length instead of the 3 (for further modifications) an only one access to the DOM (Sorry, I am reading an article about best practices).
Code:
function process(){
var fradioValue = 0, cradioCol=document.form_20443524032.dep;
for (var i = 0,l=cradioCol.length; i < l; i++){
if (cradioCol[i].checked == true){
fradioValue = parseFloat(cradioCol[i].value);}
}
}
// work with the fradioValue
}
The local variable fradioValue is only define in the function process(). If you want use it in a global scope, you have to write
Code:
var fradioValue;
function process(){
var cradioCol=document.form_20443524032.dep;
fradioValue = 0; // without var
for (var i = 0,l=cradioCol.length; i < l; i++){
if (cradioCol[i].checked == true){
fradioValue = parseFloat(cradioCol[i].value);}
}
}
// work with the fradioValue
}
// Now work too with fradioValue after a call to process
Bookmarks