I want to create an online test,but there is something wrong with my first question.The code below doesn't work and returns "your score is 0" even when the right answer is checked.
<!DOCTYPE html>
<html>sssdsdsdsd
<head>Mypage.com
<title> myPage</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<script>
var total=0;
var yourmark="your score is ";
if(document.getElementById('q12').checked) {
total=total+1;
}else {
total=total;
}
</script>
<script>
function showScore() {
alert(yourmark + total );
}
</script>
</br>
<input type="radio" name="question1" id="q11" value="false">Question 1-first option <br>
<input type="radio" name="question1" id="q12" value="true" > Question 1- second option<br>
<input type="radio" name="question1" value="false">Question 1- third option<br>
<button onclick="showScore()">Show my score</button>
</body>
</html>
http://codepen.io/anon/pen/vgJuA
So, leave var total = 0 as global variable outside the functions and create a function checkAnswer()
.
Your javascript part now will be:
var total = 0;
function checkAnswer() {
//total is the global Variable for the score
if (document.getElementById('q12').checked) {
total = total + 1;
} else {
total = total;
}
return total;
}
function showScore() {
var yourmark = "your score is ";
alert(yourmark + checkAnswer());
}
Hope it helps!