Hello i am new to web development. I created a simple test question in html5 where a user selects only one answer(using radio). This done in html and javascript. No backend. I want to make sure a radio button has been selected before moving to next question. If radio button wasn't selected, it displays an alert telling user must select an answer before moving forward.
Below is my code:
<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>
I know my javascript code is wrong.. 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) {
//
}
}
}
name="radio", but your Javascript hasform.elements['radios']. The extrasin the JS makes it not work.