Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting radio-button value on a loop

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!

like image 881
mauguerra Avatar asked May 25 '26 16:05

mauguerra


2 Answers

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

like image 190
user1370510 Avatar answered May 28 '26 04:05

user1370510


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.

like image 40
j08691 Avatar answered May 28 '26 06:05

j08691



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!