Getting the value of the radio buttons in a loop

I am working with a javascript function that takes the meaning of some questions using RadioButtons from YES or NO. To get the value of a single 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 each question, so the code becomes very long. So I am trying to create a function or loop in which the name of the question changes. My only problem is that I do not know how to use the variable on document.form1.VARIABLE.value. I already tried several ways, but did not work.

Can anyone help me with this?

Thank you so much!

+3
source share
3 answers

using

document.forms['form-name']['radio-button-name'].value

que_1 que_2, i

+2

, . ( Q1, Q2 Q3). , "aux" :

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.

+2

, (checked = yes, unchecked = no). , , . Striked out, OP "", "" " ".


( JS ) :

<form name=form1 id=form1 action="index.php">
    <p>Question 1</p>
    <label><input type="radio" name="Q1" value="yes">Yes</label>
    <label><input type="radio" name="Q1" value="no">No</label>

    <p>Question 2</p>
    <label><input type="radio" name="Q2" value="yes">Yes</label>
    <label><input type="radio" name="Q2" value="no">No</label>

    <p>Question 3</p>
    <label><input type="radio" name="Q3" value="yes">Yes</label>
    <label><input type="radio" name="Q3" value="no">No</label>

    <button id="go">Go!</button>
</form>

<script type="text/javascript">
    check = function (e) {
        e.preventDefault(); //Don't submit!
        var result = [];
        var form = document.getElementById("form1");
        for (var i = 1; typeof(form["Q" + i]) != "undefined"; i++) {
            for (var j = 0; j < form["Q" + i].length; j++) {
                if (form["Q" + i][j].checked) {
                    result.push(form["Q" + i][j].name + " " + form["Q" + i][j].value);
                }
            }
        }
        console.log(result);
    }

    button = document.getElementById("go");
    button.onclick = check;

</script>

, "!". .


"Q" i, "Q1" "Q2" ..

+1
source

All Articles