Javascript - I Can't Find My Mistake.(radio Buttons)
Solution 1:
The immediate reasons why things are not working as you want are listed.
You set the value of the total before the elements are parsed and rendered. HTML will parse from top to bottom. Therefore you want to move your script to the bottom.
If you need to set the value of the option box in the markup, use checked instead of value attribute.
You should have something like the snippet below.
<!DOCTYPE html>
<html>sssdsdsdsd
<head>Mypage.com
<title> myPage</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<script>
function showScore() {
alert(yourmark + total );
}
</script>
</br>
<input type="radio" name="question1" id="q11">Question 1-first option <br>
<input type="radio" name="question1" id="q12" checked="true" > Question 1- second option<br>
<input type="radio" name="question1">Question 1- third option<br>
<button onclick="showScore()">Show my score</button>
<script>
var total=0;
var yourmark="your score is ";
if(document.getElementById('q12').checked) {
total=total+1;
}else {
total=total;
}
</script>
</body>
</html>
Solution 2:
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!
Solution 3:
This block:
var total=0;
var yourmark="your score is ";
if(document.getElementById('q12').checked) {
total=total+1;
}else {
total=total;
}
runs at the beginning of of the page, as it is loading. At this point total
is, in fact 0
. When you click the button, all you're asking for is the value of 'total. At no point are you updating the value of
total` after you change the options.
The simplest solution, as PM 77-1 suggested, is to move the calculation inside the function, so that total
is calculated every time you need an updated answer.
<!DOCTYPE html>
<html>sssdsdsdsd
<head>Mypage.com
<title> myPage</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<script>
function showScore() {
var total=0;
var yourmark="your score is ";
if(document.getElementById('q12').checked) {
total=total+1;
}else {
total=total;
}
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>
Post a Comment for "Javascript - I Can't Find My Mistake.(radio Buttons)"