Reputation: 13
I am a beginner coder, and I am working on this quiz-type program. It needs to ask pre-created questions, and then check if you got the right answer, adjust your running score, and then show the next problem. I finished everything else, but the part that is getting me stuck is this part.
<!doctype html>
<html lang="en">
<head>
<title>Group Project</title>
</head>
<body>
<script text="text/javascript">
var a = 0;
var b = 0;
document.write(a, "/", b)
function score() {
var a = 0;
var b = 0;
if (document.question.one.value=="10") {
++a;
++b;
}
else{
++b;
}
document.write(a, "/", b)
}
</script>
<form name="question"><br>
<input type="text" name="one"/><br>
<input type="button" value="Submit" onclick="score()" />
</form>
I picked 10 in the IF statement just to see is the increment works, but what happens when I do input 10 into the text input, the page reloads, showing only the created fraction and no buttons or text inputs. How can I make it so the score or fraction runs along, and does not need a complete page reload to increment?
Upvotes: 1
Views: 356
Reputation: 1693
In addition to above answer, I would recommend the following. If you are programmatically modifying page contents, you will usually save time by using a library which presents a cleaner/more straight-forward interface. One common library for this purpose is jQuery: http://jquery.com/
Upvotes: 1
Reputation: 193261
You don't want to use document.write
as it clears all document to write new content. Instead you should change inner text content of some DOM element, like div
. For example:
<form name="question">
<div id="score"></div>
<input type="text" name="one" />
<br>
<input type="button" value="Submit" onclick="score()" />
</form>
<script text="text/javascript">
var a = 0;
var b = 0;
write(a, b);
function score() {
var a = 0;
var b = 0;
if (document.question.one.value == "10") {
++a;
++b;
} else {
++b;
}
write(a, b);
}
function write(a, b) {
document.getElementById('score').innerHTML = a + "/" + b;
}
</script>
In above code I introduced helper function write
which displays scope text in the div#score
div.
Also note that script now goes after form element, to make sure that write
function can locate div#score
when it's executed (HTML should be loaded by that time).
Upvotes: 0