2016-09-16 8 views
-2

私はJavaScriptのクイズを作っていますが、同じ名前のグループ化されたラジオボタンが同じ値を持つことができるかどうか疑問に思っていましたか?私は正解に「正しい」値を与え、他の誤った答えには、私のクイズを採点するための「間違った」値を与えたかったのです。私は他の例を探し、他の人が尋ねるのを見ていない。JavaScriptクイズ - 確認のためにラジオボタンに同じ値を設定することはできますか?

以下JavaScriptは、以下のコードは、クイズのHTMLのためのものであるスコアを

function showResults_onclick() { 
    var myForm = document.form1; 
    var totalScore = 0; 

    var Answer1 = myForm.q1.options[myForm.q1.selectedIndex].value; 
    if (Answer1 == correct) { 
    totalScore ++; 
    }; 

    myForm.showResults.value ="Congratulations your total score is " 
    + totalScore + "/1!"; 
} 

を追加するためのものです。

私は

myForm.q1.options[myForm.q1.selectedIndex].value 

のコードは、文が集計する場合、私は、その後通さ思われる、ユーザーの選択に応じて「正しい」か「間違った」を返しますどちらかと仮定した

<form name="form1" action="" method="post"> 

    <h3>Question 1: Answer is A! </h3> 
    <input type="radio" name="q1" value="correct">A</input><br> 
    <input type="radio" name="q1" value="incorrect">B</input><br> 
    <input type="radio" name="q1" value="incorrect">C</input><br> 
    <input type="radio" name="q1" value="incorrect">D</input> 
    <br><br> 


    <input type="button" name="submitAnswers" value="Submit" 
    onclick="showResults_onclick()"> 
    <br><br><br> 

    <textarea name="showResults" rows="8" cols="40"></textarea> 
</form> 

スコア。

エラーが

捕捉されない例外TypeErrorを言う:プロパティを読み取ることができません '未定義' 未定義

の同じ行のため

myForm.q1.options[myForm.q1.selectedIndex].value; 

助けてくれてありがとう!

+1

提供された「HTML」には何もありません...あなたは何を参照していますか? – Rayon

+0

'myForm.q1.options [myForm.q1.selectedIndex] .value'はラジオボタングループではなく' q1'という 'select'メニューに適用されます。また、値として「正しい」を指定すると、コードを正確に見て人々は簡単に100%を得ることができます – RamRaider

+0

ああ、そうですよ!私はそれがオプションが提供される必要がある選択フィールドと完全に混ざった。知らせてくれてありがとうございます! – peakersky

答えて

1

I ... was wondering if radio buttons grouped with the same name could have same values?

はい、問題ありません。

I was assuming that the code of

myForm.q1.options[myForm.q1.selectedIndex].value

would either return ‘correct’ or ‘incorrect’ depending on the users’ choice, which I would then put through the if statement to tally the scores.

the error says

Uncaught TypeError: Cannot read property 'undefined' of undefined

q1optionsを持っていないので。 optionsは、ラジオボタンではなく、selectの要素に関連しています。

選択したラジオボタンの値を取得するには:

  1. :checked pseudo-classを使用します。

    var selectedButton = document.querySelector("input[name=q1]:checked"); 
    var value = selectedButton ? selectedButton.value : null; 
    
  2. ループを使用します。

    var value; 
    for (var i = 0; i < myForm.q1.length; ++i) { 
        if (myForm.q1[i].checked) { 
         value = myForm.q1[i].value; 
         break; 
        } 
    } 
    
  3. は、ビルトインを使用しますES2015 +のループ:

    let selectedButton = Array.from(myForm.q1).find(b => b.checked); 
    let value = selectedButton ? selectedButton.value : null; 
    
+0

Tさん、ありがとう。J Crowder、それは本当に良いコーディングです – peakersky

関連する問題