Home > Back-end >  How do I know if a user has selected an option in a form in html javascript
How do I know if a user has selected an option in a form in html javascript

Time:02-05

I am trying to build a quiz with questions and options but I don't know how to add the options to the quiz. Also, I want to know if I selected the correct option and if the number of correct answers is shown at the end. Can someone help me build this? I have tried adding options but I can't get the output needed.

  <form align="center" id = "test">
    Question 1: <input type="radio" name="radiogroup1" value="radio" id="radiogroup1"> Option 1
    <input type="radio" name="radiogroup1" value="radio" id="radiogroup2"> Option 2 <br><be>
    </form>

CodePudding user response:

This is quick solution for you to understand.

Js:

const questions = [
    { 
        question: 'Are you adult?',
        key: 'adult',
        answers: ['yes', 'no'],
    }];

 const validAnswers = {
     adult: "yes"
 };

 function onClick(e) {
     const questionName = e.target.name;
     const questionValue = e.target.value;

     if (validAnswers[questionName] === questionValue) {
          console.log('is adult')
          // do whatever you want with valid answer
     } else {
         // or do something else.
         console.log('not an adult')
   }
}

function createQuestion() {
    let generatedHTML = '';
    questions.forEach(({ question, key, answers }) => {
    generatedHTML  = `<label for="${key}">${question}</label>`  
    // creating options dinamically
        answers.forEach((value) => {
            generatedHTML  = createRadioButton(key, value);
        });
    generatedHTML  = `<br />`;
 })

  document.getElementById("my-form").innerHTML = generatedHTML;
}

function createRadioButton(key, value) {
    return `<input type="radio" id="${key}" name="${key}" 
             value="${value}"          onclick=onClick(event)>`;
}

   createQuestion();

CodePudding user response:

See if this helps you: (just an example to get the idea)

function submitAnswers() {
  var total = 5;
  var score = 0;
  //Get user input
  var q1 = document.forms["quizForm"]["q1"].value;
  var q2 = document.forms["quizForm"]["q2"].value;
  var q3 = document.forms["quizForm"]["q3"].value;
  var q4 = document.forms["quizForm"]["q4"].value;
  var q5 = document.forms["quizForm"]["q5"].value;

  // Validation
  for (var i = 1; i <= total; i  ) {
    if (eval('q'   i) == null || eval('q'   i) == '') {
      alert("you missed question "   i);
      return false;
    }
  }

  //set correct answers
  var answers = ["b", "d", "c", "a", "b"]

  //check answers
  for (var i = 1; i <= total; i  ) {
    if (eval('q'   i) == answers[i - 1]) {
      score  ;
    }
  }
  alert('You scored '   score   " out of "   total);
  
  return false;
}
<div >
  <section>
    <form name="quizForm" onsubmit="submitAnswers(); return false">
      <h3>1. Question number one?</h3>
      <input type="radio" name="q1" value="a" id="q1a"> a. answer11<br>
      <input type="radio" name="q1" value="b" id="q1b"> b. answer12<br>
      <input type="radio" name="q1" value="c" id="q1c"> c. answer13<br>
      <input type="radio" name="q1" value="d" id="q1d"> d. answer14<br>

      <h3>2. Question number two?</h3>
      <input type="radio" name="q2" value="a" id="q2a"> a. answer21<br>
      <input type="radio" name="q2" value="b" id="q2b"> b. answer22<br>
      <input type="radio" name="q2" value="c" id="q2c"> c. answer23<br>
      <input type="radio" name="q2" value="d" id="q2d"> d. answer24<br>

      <h3>3. Question number three?</h3>
      <input type="radio" name="q3" value="a" id="q3a"> a. answer31<br>
      <input type="radio" name="q3" value="b" id="q3b"> b. answer32<br>
      <input type="radio" name="q3" value="c" id="q3c"> c. answer33<br>
      <input type="radio" name="q3" value="d" id="q3d"> d. answer34<br>

      <h3>4. Question number four ?</h3>
      <input type="radio" name="q4" value="a" id="q4a"> a. answer41<br>
      <input type="radio" name="q4" value="b" id="q4b"> b. answer42<br>
      <input type="radio" name="q4" value="c" id="q4c"> c. answer43<br>
      <input type="radio" name="q4" value="d" id="q4d"> d. answer44<br>

      <h3>5. Question number five ?</h3>
      <input type="radio" name="q5" value="a" id="q5a">a. answer51<br>
      <input type="radio" name="q5" value="b" id="q5b">b. answer52<br>

      <br><br>
      <input type="submit" value="Submit Answers">
    </form>
  </section>

</div>

  • Related