overflowstack9 overflowstack9 - 1 year ago 62
Javascript Question

How to get quiz test score as text without popup

I want to implement online quiz in my blog. Below is my code after selecting all the options when user click view results it displays result score as popup.

But i want to display as result as text in the form itself as shown in the below image.


var answers = ["A","C","B"],
tot = answers.length;

function getCheckedValue( radioName ){
var radios = document.getElementsByName( radioName ); // Get radio group by-name
for(var y=0; y<radios.length; y++)
if(radios[y].checked) return radios[y].value; // return the checked value

function getScore(){
var score = 0;
for (var i=0; i<tot; i++)
if(getCheckedValue("question"+i)===answers[i]) score += 1; // increment only
return score;

function returnScore(){
alert("Your score is "+ getScore() +"/"+ tot);

<h3>How many letters are there in "ZZ"?</h3>
<input type="radio" name="question0" value="A">2<br>
<input type="radio" name="question0" value="B">1<br>
<input type="radio" name="question0" value="C">3<br>
<input type="radio" name="question0" value="D">4<br>
<h3>How many letters are there in "ZZX"?</h3>
<input type="radio" name="question1" value="A">2<br>
<input type="radio" name="question1" value="B">1<br>
<input type="radio" name="question1" value="C">3<br>
<input type="radio" name="question1" value="D">4<br>
<h3>How many letters are there in "V"?</h3>
<input type="radio" name="question2" value="A">2<br>
<input type="radio" name="question2" value="B">1<br>
<input type="radio" name="question2" value="C">3<br>
<input type="radio" name="question2" value="D">4<br>

<button onclick="returnScore()">View Results</button>

Answer Source

You need to make a place in the DOM for the score to go.

<div id="show-score"></div>

Then use the returnScore function to place the result there instead of alerting.

function returnScore(){
    document.getElementById('show-score').innerHTML = 
       "Your score is "+ getScore() +"/"+ tot;

See fiddle: https://jsfiddle.net/7Ly00p2z/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download