2015-04-04 55 views
-1

此时我只是测试以查看是否可以将所选单选按钮与数组中的正确答案进行比较。请参阅下面的评论:检查单选按钮的选择是否与使用JavaScript或jQuery的数组中的项目匹配

var allQuestions = [{ 
     "question": "Who was Luke's wingman in the battle at Hoth?", 
     "choices": ["Dak", "Biggs", "Wedge", "fx-7"], 
     "correctAnswer": 0 
    }]; 


function answerFwd() { 
    var answerOutput = " "; 
    var itemAnswers = allQuestions; 
    var answer = 0; 
    var playerTally = 0; 
    var playerFeedback = ""; 
    var playerMessage = document.getElementById("playerMessage"); 


    // Is this the correct way to store the radio button which is selected? 
    var radioValue = $("input[type='radio'].radioButtons").is(':checked'); 

    var right = false; 

    if (currentAnswer <= itemAnswers.length) { 
     currentAnswer++; 
    } 

    createRadioButtonFromArray(itemAnswers[currentQuestion].choices); 

    //Then compare value in array with radioValue value 
    if(radioValue == itemAnswers.correctAnswer){ 
      right = true; 
    }   

    if(right) { 
     alert("You answered correctly"); 
    } else { 
     alert("Wrong answer"); 
    } 

}

我怀疑我的错误是我没有与radioValue正确比较correctAnswer:3。有意义的是按钮的索引与值匹配。 for-loop会是最好的方式吗? 在此先感谢!

UPDATE

这是创建按钮的代码:

function createRadioButtonFromArray(array) { 
    var len = array.length; 
    var responses = document.getElementById("responses"); 
    responses.innerHTML = ''; 
    for (var i = 0; i < len; i++) { 
    radio = document.createElement("input"); 
    radio.type = "radio"; 
    radio.name = "choices"; 
    radio.className = "radioButtons"; 
    radio.value = i; 
    radio.id = "choice" + i; 
    var radioText = document.createElement("div"); 
    radioText.id = "c" + i; 
    radioText.className = "choiceText"; 
    radioText.innerHTML = array[i]; 
    responses.appendChild(radio); 
    responses.appendChild(radioText); 
    } 
} 

这是如何呈现:

<div id="responses"> 
<input type="radio" name="choices" class="radioButtons" value="0" id="choice0"> 
<div id="c0" class="choiceText">The Avenger</div> 
<input type="radio" name="choices" class="radioButtons" value="1" id="choice1"> 
<div id="c1" class="choiceText">Devastator </div> 
<input type="radio" name="choices" class="radioButtons" value="2" id="choice2"> 
<div id="c2" class="choiceText">Conquest</div> 
<input type="radio" name="choices" class="radioButtons" value="3" id="choice3"> 
<div id="c3" class="choiceText">The Executor</div> 

+2

尔,安达是卢克的炮手* *,而不是他的僚机。 – 2015-04-04 21:42:57

+0

太棒了!这是真的.. – 2015-04-04 21:44:21

+0

*“'

The Avenger
'”*您正在寻找的元素是['label'](http://www.w3.org/TR/html5/forms.html#the-label -元件)。 – 2015-04-04 22:22:34

回答

0

是这个正确的方式来存储所选的单选按钮?

var radioValue = $("input[type='radio'].radioButtons").is(':checked'); 

不,这将是:

var radioValue = $("input[type='radio'].radioButtons:checked").val(); 

More

+0

这工作有点,我想我仍然不正确地匹配单选按钮的值与数组中的值。有任何想法吗? – 2015-04-04 21:53:06

+0

为了给一些背景,我正在尝试做一个测验......如果现在不明显.. :) – 2015-04-04 21:54:02

+0

@AntonioOrtiz:如果您显示单选按钮,它将有助于*很多*。 – 2015-04-04 22:06:53

相关问题