2015-04-04 51 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

相關問題