简体   繁体   中英

How to disable a group of radio buttons if one has been selected and display an alert if one is not selected and the next button is clicked

I am trying to disable the rest of the radio buttons if one has been selected for a multiple-choice quiz. I tried using a forEach loop but it is skipping the forEach loop and just triggering the alert box in the else part of the if statement when I click a radio button before one is even selected. Here is the function I am working in. the name${questionNumber} is the way to call my radio buttons. The myQuestions is my object with all of the questions and answers stored in it. Can someone please help me figure out how to do this, I would appreciate it. Thanks.

 function showExplanation(questionNumber) { document.getElementsByClassName("explanations")[questionNumber].classList.add("show"); if (document.getElementsByName(`name${questionNumber}`).checked) { myQuestions.forEach((questionNumber) => { document.getElementsByName(`name${questionNumber}`).disabled = true; }); } else { alert("Please select an answer."); } } const myQuestions = [{ question: "What color is the sky?", answers: { a: "blue", b: "green", c: "red", d: "yellow" }, explanation: { correct: "Correct answer: A. blue", explain: `The sky may be blue today `, source: "Source: common sense" }, correctAnswer: "a" }, { question: `What color is an elephant?`, answers: { a: "blue", b: "grey", c: "black", d: "green" }, explanation: { correct: "Correct answer: B. grey", explain: `Most elephants are grey `, source: "Source: life experience" }, correctAnswer: "b" } ];
 <!-- START OF QUIZ--> <div id="border" class="uk-align-center uk-width-1-2"> <div class="quiz-body"> <h1 class="h1-quiz">Test Your Knowledge</h1> <div class="quiz-container"> <div id="quiz"></div> </div> <div id="results" class="uk-text-center uk-text-large uk-text-bold uk-margin-small-top"></div> </div>

You mean When Correct User Can Only Choose one answer and when User select one answer other's will be disabled??

What is your HTML code look like??

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM