单选按钮上的必需属性无法正常运行

时间:2018-05-04 13:43:31

标签: javascript jquery

我已针对此问题尝试了多个建议的修复方法,包括仅在一个输入上使用required属性并使用required =“required”。在这一点上,我不知道该怎么做。对解决方案的任何建议都会非常有帮助。感谢您的时间!这是我的代码:

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>`;
}

以下是整个项目的链接,如果您有兴趣:

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

2 个答案:

答案 0 :(得分:1)

submitButton()功能中,您可以检查是否未选择任何答案,显示提醒并返回:

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

答案 1 :(得分:0)

如果您想在默认情况下选择一个单选按钮,请使用:

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>