JoshingYou
JoshingYou

Reputation: 11

Required Attribute on a Radio Button Not Functioning Correctly

I have tried multiple suggested fixes for this problem including using the required attribute on only one input and using required="required." At this point, I'm not sure what to do. Any advice on a solution would be really helpful. Thank you for your time! Here's my code:

function questionGenerator(score, multipleChoiceQues, completedQuestions) {
  return `
    <form role="form" class="question-form">
      <fieldset>
        <legend>${multipleChoiceQues.question}</legend>
          <label class="choice">
            <input type="radio" name="option" id="ans" value="${multipleChoiceQues.answerOne}" required>
            <span>${multipleChoiceQues.answerOne}</span>
          </label>
          <br>
          <label class="choice">
            <input type="radio" name="option" id="ans" value="${multipleChoiceQues.answerTwo}" required>
            <span>${multipleChoiceQues.answerTwo}</span>
          </label>
          <br>
          <label class="choice">
            <input type="radio" name="option" id="ans" value="${multipleChoiceQues.answerThree}" required>
            <span>${multipleChoiceQues.answerThree}</span>
          </label>
          <br>
          <label class="choice">
            <input type="radio" name="option" id="ans" value="${multipleChoiceQues.answerFour}" required>
            <span>${multipleChoiceQues.answerFour}</span>
          </label>
          <br>
          <button class="answer-submit">SUBMIT</button>
      </fieldset>
    </form>


    <section class="question-and-score">
      <span class="currentQuestion">Question: ${multipleChoiceQues.num}/10</span>
      <span class="currentScore">Score: ${score}/${completedQuestions}</span>
    </section>`;
}

Here's the link to the entire project, if you're interested:

https://repl.it/@joshing_you/Fortnite-Battle-Royale-Quiz-App

Upvotes: 1

Views: 48

Answers (2)

Will Jenkins
Will Jenkins

Reputation: 9787

In your submitButton() function, you can check if no answer has been selected, show an alert and return:

const answer = $("input:checked").siblings("span");
if(answer.length===0){
    alert("please select an answer");
    return;
}

Upvotes: 1

Ggs
Ggs

Reputation: 191

If you wants to select a radio button by default use :

checked="checked"

<form>
  Select Gender:

  <label><input type="radio" name="gender" value="male" required>Male</label>

  <label><input type="radio" name="gender" value="female">Female</label>

  <input type="submit">
</form>

Upvotes: 1

Related Questions