-3

I'm still new to JavaScript, and I'm trying to write a quiz that will send a person to one of 3 pages depending on the answers they choose (so each time they pick an "x" answer, x will increase by one).

With the code I've written so far I've got two problems.

  • The variable values aren't increased by one so maybe I've written that wrong.

  • I'm not sure how to pick the variable with the most checked answers to send them to the relating page.

I tried writing an if statement to show what I mean. Any thoughts on how to improve this would be greatly appreciated, or if a whole other approach would be better I'm open to that.

var x = 0;
var y = 0;
var z = 0;

function question1(){
    if (document.getElementById('a1').checked) {
        x++;        
    }
    else if (document.getElementById('a2').checked) {
        y++; 

    } else if(document.getElementById('a3').checked){
        z++;
    }
}
function question2(){
    if (document.getElementById('b1').checked) {
        x++;        
    }
    else if (document.getElementById('b2').checked) {
        y++; 

    } else if(document.getElementById('b3').checked){
        z++;
    }
}
function result(){
    Math.max(x,y,z);
    if (x){
       alert("You chose x");
    } else if (y){
        alert("You chose y");
      } else if (z){
          alert("You chose z");
        }

}
4

1 に答える 1

0

あなたはこのようなものを探していますか:

var totals = [0, 0, 0];
var letters = ["a", "b", "c"];

//Go through all answer letters
for (var i = 0, lt = letters.length; i < lt; i++)
{
    //Each question has 3 possible answers
    for (var j = 0; j < 3; j++)
    {
        if (document.getElementById(letters[i] + (j + 1)).checked)
        {
           //Increase the total that corresponds to the answer number
           totals[j]++;
           break;
        }
    }
}

totals.sort(function(a,b){return a-b});

var highest = totals.pop();
于 2012-12-15T18:41:33.677 に答える