I am working with a javascript function which takes the value of some questions using RadioButtons of YES or NO. To get the value of one question(Q1) I do something like this:
for (i=0; i<document.form1.Q1.length; i++){
if(document.form1.Q1[i].checked)
Array[0] = document.form1.Q1[i].value;
}
I have to do this for every question, so the code is getting very long. So I am trying to make a function or a loop in which the name of the question is changing. My only problem is that i dont know how to use a Variable on document.form1.VARIABLE.value. I already tried some ways but didnt work.
Can anyone help me with this?
Thanks a lot!
use
document.forms['form-name']['radio-button-name'].value
and give radio button names like que_1 que_2 so you can change that with i using string concatenation
Here's a loop that will traverse your radio buttons and build an array with the values. In the code and example, it's set for testing three questions (named Q1, Q2, and Q3). When done, the array "aux" contains the list of checked values:
var max = 3;
var aux = new Array();
function getCheckedValue(groupName) {
var radios = document.getElementsByName(groupName);
for (i = 0; i < radios.length; i++) {
if (radios[i].checked) {
return radios[i].value;
}
}
return null;
}
function check() {
for(var i=1;i<=max;i++) {
//console.log(i,getCheckedValue('Q'+i));
aux[i-1] = getCheckedValue('Q'+i);
}
console.log(aux);
}
jsFiddle example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With