jQuery Mobile: Create a Multiple Choice Quiz with Feedback

jQuery Mobile is a framework that quickly helps to beautifully style forms for mobile devices since it includes CSS to do all the work for us. If you aren’t sure what jQuery Mobile is or how to get started then I recommend you take a quick look at jQuery Mobile: How to Create Your First Page.

The code you would use to create radio buttons which will be grouped vertically by implementing the data-role of “controlgroup” can be found at jQuery Mobile: How to Create Radio Buttons.

The code below contains an example of how you can use JavaScript to provide immediate feedback based on verifying which radio button was selected by the user. After the “Check Answer” button is clicked, myFunction() is invoked and the text “true” or “false” is displayed.

If the correct answer is selected, which is identified via the id=”apple” placed within the form, the text “true” is displayed using the HTML DOM innerHTML property. This boolean value of “true” has been assigned to the variable “x” and represents the fact that the radio button is selected or “checked”.

 <div data-role="header">
 <h1>French Quiz</h1>
 </div>
 
 <div data-role="main" class="ui-content">
 <form class="ui-field-contain">
 <fieldset data-role="controlgroup">
 <legend>How do you say 'apple' in French?</legend>
 
 <label for="pear">la poire</label>
 <input type="radio" name="apple" id="pear" value="pear">
 
 <label for="apple">la pomme</label>
 <input type="radio" name="apple" id="apple" value="apple"> 
 
 <label for="banana">la banane</label>
 <input type="radio" name="apple" id="banana" value="banana"> 
 </fieldset>
 </form>

 <button onclick="myFunction()">Check Answer</button>

 <p id="answer"></p>

 <script>
 function myFunction() {
  var x = document.getElementById("apple").checked;
  document.getElementById("answer").innerHTML = x;
 }
 </script>

The code above will generate the following in a browser:

jQuery Mobile multiple choice quiz with feedback using innerHTML

Alternatively, you could have used a jQuery Mobile popup widget which will be covered in the next post.

 

Comments (0)

Leave a Comment