您好,我是網絡開發新手。我在html5中創建了一個簡單的測試問題,其中用戶只選擇一個答案(使用無線電)。這在HTML和JavaScript中完成。沒有後端。我想確定在轉移到下一個問題之前已經選擇了一個單選按鈕。如果單選按鈕沒有被選中,它會顯示一個警告,告訴用戶在前進之前必須選擇一個答案。如何檢查單選按鈕是否使用javascript選擇
下面是我的代碼:
<section>
<p class="questions">Given points (X1, Y1) and (X2, Y2) select the formula to find the equation of the given line.</p>
<div >
<form class="answers">
<input type="radio" name="radio" value="correct">
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<mrow>
<mi> y</mi>
<mo>=</mo>
<mi>m</mi>
<mo>⁢</mo>
<mi>x</mi>
<mo>+</mo>
<mi>b</mi>
</mrow>
</math>
<!-- 2nc choice -->
<input type="radio" name="radio" value="incorrect" >
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<mrow>
<mrow>
<mo>(</mo>
<mi>x</mi>
<mo>-</mo>
<mi>h</mi>
<msup>
<mo>)</mo>
<mn>2</mn>
</msup>
</mrow>
<mo>+</mo>
<mrow>
<mo>(</mo>
<mi>y</mi>
<mo>-</mo>
<mi>k</mi>
<msup>
<mo>)</mo>
<mn>2</mn>
</msup>
</mrow>
<mo> = </mo>
<mrow>
<msup>
<mi> r</mi>
<mn>2</mn>
</msup>
</mrow>
</mrow>
</math> <br>
<!-- 3rd choice -->
<input type="radio" name="radio" value="incorrect">
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<mrow>
<mrow>
<mi>y</mi>
<mo>-</mo>
<msub>
<mi>y</mi>
<mn>1</mn>
</msub>
</mrow>
<mo> = </mo>
<mrow>
<mi>m</mi>
<mo>⁢</mo>
<mo>(</mo>
<mi>x</mi>
<mo>-</mo>
<msub>
<mi>x</mi>
<mn>1</mn>
</msub>
<mo>)</mo>
</mrow>
</mrow>
</math>
<!--4th Choice -->
<input type="radio" name="radio" value="incorrect">
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<mrow>
<mrow>
<mi>y</mi>
<mo>-</mo>
<msub><mi>y</mi><mn>2</mn></msub>
</mrow>
<mo> = </mo>
<mrow>
<mfrac>
<mrow>
<msub><mi>y</mi><mn> 2</mn></msub>
<mo> - </mo><msub><mi> y</mi><mn> 1</mn></msub>
</mrow>
<mrow>
<msub><mi>x</mi><mn> 2</mn></msub>
<mo> - </mo><msub><mi> x</mi><mn> 1</mn></msub>
</mrow>
</mfrac>
</mrow>
<mrow>
<!-- <mo>⁢</mo> -->
<mo>(</mo>
<mi> x </mi>
<mo> - </mo>
<msub><mi> x</mi><mn>2</mn></msub>
<mo>).</mo>
</mrow>
</mrow>
</math>
<br>
<!-- submit button -->
<input type="submit" value="Submit & Next Question" onclick="getAnswer1(this.form)">
<!-- clears the radio -->
<input type="submit" value="Cancel & Clear Selection" onclick="">
</form>
</div>
</section>
<script type="text/javascript" src="script.js"></script>
我知道我的JavaScript代碼是錯誤.. 的Javascript:
/**Trouble making sure user selects an input doesn't matter if its wrong or right. An alert should displayed if user attempts to go to next question. Must select an option. **/
//global array stores answers
var results = [];
function getAnswer1(form) {
var radios = form.elements['radio'];
for(var i = 0; i < radios.length; i++) {
if(radios[i].checked) {
//
}
}
}
你的HTML有'NAME = 「無線電」',但你的Javascript有'form.elements ['radios']'。 JS中額外的's'使它無法工作。 – Barmar
@Bamar哦是的我糾正,謝謝你將在 – user3497437