簡體   English   中英

檢查用戶是否選擇了正確的復選框

[英]Checking if the user selected the correct checkbox

我正在使用 javascript 進行測驗,但在從所選復選框中獲取答案時遇到了問題。 我已經讓復選框起作用,這樣你只能選擇一個答案。 使用復選框的原因只是我嘗試使用單選框,但我也沒有讓它以這種方式工作。

目前我的表格是這樣的:

    <div id="vastausformi">
        <form id="vastaukset"> 

            <label for="a">A)</label>
<input type="checkbox" classname="box" id="Check1" value="Value1" onclick="selectOnlyThis(this.id)" />  
    
            <label for="b">B)</label>
  <input type="checkbox" classname="box" id="Check2" value="Value1" onclick="selectOnlyThis(this.id)" />  
             
            <label for="c">C)</label>
<input type="checkbox" classname="box"  id="Check3" value="Value1" onclick="selectOnlyThis(this.id)" />   

            <label for="d">D)</label>
<input type="checkbox" classname="box" id="Check4" value="Value1" onclick="selectOnlyThis(this.id)" /> 
        </form>
    </div>

然后我有一個問題的javascript:

let questions= {

  question: "Which city is the capital of Sweden?",
  vastaus:{
      a: 'Stockholm',
      b: 'Malmö',
      c: 'Göteborg',
      d: 'Helsingborg'
  },
  correctAnswer: 'a'
};

然后我做了一個檢查用戶猜測的函數。

  function checkGuess(){
    let correctAnswer= questions.valueOf(oikeaVastaus);
    let playerChoice= document.getElementsByClassName("box");
    
    if(playerChoice===correctAnswer){
      console.log("correct");
    }

    else{
      console.log("wrong");
    }

   
  };
    
guessSubmit.addEventListener('click', checkGuess);

checkGuess 函數似乎沒有得到“答案”。 我明白了,所以它說答案是正確的(無論你選擇哪個復選框)或者所有答案都是錯誤的。 我試圖用不同的方式從復選框中“檢索”信息,但沒有成功。 我似乎無法掌握那個“正確答案”。 我還嘗試將一個特定的復選框設置為“正確的選擇”,這樣每次您選擇它時,它都是正確的,但這也不起作用。 所以 checkGuess 函數只是我嘗試進行檢查的方法之一。 我也試圖放棄 playerChoice 的聲明並將輸入直接放在 if 語句中。 我也試過

使用這些控制台日志的原因只是為了查看腳本是否有效,因此將來答案將顯示在屏幕上並且問題會不止一個。 我是編碼新手,所以我可能完全錯了,但我想讓它出現一個問題,然后有四個復選框可供選擇,然后會有一個按鈕進入下一個問題。

我為我的英語道歉,但希望你能理解我的意思。

如果有人知道如何讓它工作或有其他方法可以做到這一點,我將不勝感激!

我已將輸入更新為使用radio而不是checkbox ,以允許用戶一次選擇一個答案

此外,單擊輸入將立即使用其值調用checkGuess方法

 let questions= { question: "Which city is the capital of Sweden?", vastaus:{ a: 'Stockholm', b: 'Malmö', c: 'Göteborg', d: 'Helsingborg' }, correctAnswer: 'a' }; function checkGuess(playerChoice){ if(playerChoice === questions.correctAnswer){ console.log("correct"); } else{ console.log("wrong"); } };
 <div id="vastausformi"> <form id="vastaukset"> <label for="a">A)</label> <input type="radio" classname="box" name="box" id="Check1" value="a" onclick="checkGuess(this.value)" /> <label for="b">B)</label> <input type="radio" classname="box" name="box" id="Check2" value="b" onclick="checkGuess(this.value)" /> <label for="c">C)</label> <input type="radio" classname="box" name="box" id="Check3" value="c" onclick="checkGuess(this.value)" /> <label for="d">D)</label> <input type="radio" classname="box" name="box" id="Check4" value="d" onclick="checkGuess(this.value)" /> </form> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM