How to repeat a process by calling a function in javascript












1















I recently proposed this simple feature in a previous post by using prompt() to acquire user inputs. Since then, I have elevated myself to use HTML form inputs to reach a similar result. I am unable to get the equation to refresh. I am not sure what I am doing wrong. Simply...



-Random generate two numbers between 1-10...works only once



-User inputs an answer and compare...works



-Tally total answers and correct answers...works



-Provide a number grade...works



The math generation "getMath()" does not re-run at the end of the "result()" and I am not sure why.



Please feel free to beat me up on syntax.



Moving forward, I will be adding digits and changing the operation to incrementally increase the difficulty level. But one step at a time.



Thank you in advance for your time and insight.






var correct = 0,
wrong = 0,
ans,
firstnum = Math.floor(Math.random() * 10 + 1),
secondnum = Math.floor(Math.random() * 10 + 1),
total = firstnum + secondnum,
score,
input,
calc = "+";

function getMath() {

document.getElementById("firstnum").value = firstnum;
document.getElementById("secondnum").value = secondnum;
document.getElementById("calc").value = calc;
}

function getAnswer() {

var input = document.getElementById("userInput").value;
if (input == total) {
correct++;
} else {
wrong++;
}
result();
}


function result() {

score = correct + wrong;
percent = correct / score;
document.getElementById("score").innerHTML = score;
document.getElementById("ans").innerHTML = correct;
document.getElementById("percent").innerHTML = percent * 100;
getMath();
}

<body onload="getMath()">

<h1>Math Test</h1>

<input type="text" id="firstnum"></input>
<input type="text" id="calc">
<input type="text" id="secondnum">
<hr>

<form id="form1" onsubmit="return false">
<input type="text" id="userInput" placeholder="" size="10">
<button onclick="getAnswer()">Submit Answer</button>
</form>

<p>Total Answered</p>
<p id="score"></p>
<p>Answered Correctly</p>
<p id="ans"></p>
<p>Your number grade</p>
<p id="percent">%</p>

</body>

</html>












share|improve this question

























  • Is placing a function at the end of result() not valid?

    – Daryl Kriefall
    Nov 25 '18 at 22:55











  • The math generation "getMath()" does not re-run at the end of the "result()" and I am not sure why. It looks like it is running once on load, and once again after submitting an answer.

    – ksav
    Nov 25 '18 at 22:57













  • Do you want to rerun getmath() when any of the values in firstnum, secondnum or calc are changed?

    – ksav
    Nov 25 '18 at 22:59











  • After calculating the user input and true/false, I want to generate a new set of numbers to calculate another user input.

    – Daryl Kriefall
    Nov 25 '18 at 23:13
















1















I recently proposed this simple feature in a previous post by using prompt() to acquire user inputs. Since then, I have elevated myself to use HTML form inputs to reach a similar result. I am unable to get the equation to refresh. I am not sure what I am doing wrong. Simply...



-Random generate two numbers between 1-10...works only once



-User inputs an answer and compare...works



-Tally total answers and correct answers...works



-Provide a number grade...works



The math generation "getMath()" does not re-run at the end of the "result()" and I am not sure why.



Please feel free to beat me up on syntax.



Moving forward, I will be adding digits and changing the operation to incrementally increase the difficulty level. But one step at a time.



Thank you in advance for your time and insight.






var correct = 0,
wrong = 0,
ans,
firstnum = Math.floor(Math.random() * 10 + 1),
secondnum = Math.floor(Math.random() * 10 + 1),
total = firstnum + secondnum,
score,
input,
calc = "+";

function getMath() {

document.getElementById("firstnum").value = firstnum;
document.getElementById("secondnum").value = secondnum;
document.getElementById("calc").value = calc;
}

function getAnswer() {

var input = document.getElementById("userInput").value;
if (input == total) {
correct++;
} else {
wrong++;
}
result();
}


function result() {

score = correct + wrong;
percent = correct / score;
document.getElementById("score").innerHTML = score;
document.getElementById("ans").innerHTML = correct;
document.getElementById("percent").innerHTML = percent * 100;
getMath();
}

<body onload="getMath()">

<h1>Math Test</h1>

<input type="text" id="firstnum"></input>
<input type="text" id="calc">
<input type="text" id="secondnum">
<hr>

<form id="form1" onsubmit="return false">
<input type="text" id="userInput" placeholder="" size="10">
<button onclick="getAnswer()">Submit Answer</button>
</form>

<p>Total Answered</p>
<p id="score"></p>
<p>Answered Correctly</p>
<p id="ans"></p>
<p>Your number grade</p>
<p id="percent">%</p>

</body>

</html>












share|improve this question

























  • Is placing a function at the end of result() not valid?

    – Daryl Kriefall
    Nov 25 '18 at 22:55











  • The math generation "getMath()" does not re-run at the end of the "result()" and I am not sure why. It looks like it is running once on load, and once again after submitting an answer.

    – ksav
    Nov 25 '18 at 22:57













  • Do you want to rerun getmath() when any of the values in firstnum, secondnum or calc are changed?

    – ksav
    Nov 25 '18 at 22:59











  • After calculating the user input and true/false, I want to generate a new set of numbers to calculate another user input.

    – Daryl Kriefall
    Nov 25 '18 at 23:13














1












1








1








I recently proposed this simple feature in a previous post by using prompt() to acquire user inputs. Since then, I have elevated myself to use HTML form inputs to reach a similar result. I am unable to get the equation to refresh. I am not sure what I am doing wrong. Simply...



-Random generate two numbers between 1-10...works only once



-User inputs an answer and compare...works



-Tally total answers and correct answers...works



-Provide a number grade...works



The math generation "getMath()" does not re-run at the end of the "result()" and I am not sure why.



Please feel free to beat me up on syntax.



Moving forward, I will be adding digits and changing the operation to incrementally increase the difficulty level. But one step at a time.



Thank you in advance for your time and insight.






var correct = 0,
wrong = 0,
ans,
firstnum = Math.floor(Math.random() * 10 + 1),
secondnum = Math.floor(Math.random() * 10 + 1),
total = firstnum + secondnum,
score,
input,
calc = "+";

function getMath() {

document.getElementById("firstnum").value = firstnum;
document.getElementById("secondnum").value = secondnum;
document.getElementById("calc").value = calc;
}

function getAnswer() {

var input = document.getElementById("userInput").value;
if (input == total) {
correct++;
} else {
wrong++;
}
result();
}


function result() {

score = correct + wrong;
percent = correct / score;
document.getElementById("score").innerHTML = score;
document.getElementById("ans").innerHTML = correct;
document.getElementById("percent").innerHTML = percent * 100;
getMath();
}

<body onload="getMath()">

<h1>Math Test</h1>

<input type="text" id="firstnum"></input>
<input type="text" id="calc">
<input type="text" id="secondnum">
<hr>

<form id="form1" onsubmit="return false">
<input type="text" id="userInput" placeholder="" size="10">
<button onclick="getAnswer()">Submit Answer</button>
</form>

<p>Total Answered</p>
<p id="score"></p>
<p>Answered Correctly</p>
<p id="ans"></p>
<p>Your number grade</p>
<p id="percent">%</p>

</body>

</html>












share|improve this question
















I recently proposed this simple feature in a previous post by using prompt() to acquire user inputs. Since then, I have elevated myself to use HTML form inputs to reach a similar result. I am unable to get the equation to refresh. I am not sure what I am doing wrong. Simply...



-Random generate two numbers between 1-10...works only once



-User inputs an answer and compare...works



-Tally total answers and correct answers...works



-Provide a number grade...works



The math generation "getMath()" does not re-run at the end of the "result()" and I am not sure why.



Please feel free to beat me up on syntax.



Moving forward, I will be adding digits and changing the operation to incrementally increase the difficulty level. But one step at a time.



Thank you in advance for your time and insight.






var correct = 0,
wrong = 0,
ans,
firstnum = Math.floor(Math.random() * 10 + 1),
secondnum = Math.floor(Math.random() * 10 + 1),
total = firstnum + secondnum,
score,
input,
calc = "+";

function getMath() {

document.getElementById("firstnum").value = firstnum;
document.getElementById("secondnum").value = secondnum;
document.getElementById("calc").value = calc;
}

function getAnswer() {

var input = document.getElementById("userInput").value;
if (input == total) {
correct++;
} else {
wrong++;
}
result();
}


function result() {

score = correct + wrong;
percent = correct / score;
document.getElementById("score").innerHTML = score;
document.getElementById("ans").innerHTML = correct;
document.getElementById("percent").innerHTML = percent * 100;
getMath();
}

<body onload="getMath()">

<h1>Math Test</h1>

<input type="text" id="firstnum"></input>
<input type="text" id="calc">
<input type="text" id="secondnum">
<hr>

<form id="form1" onsubmit="return false">
<input type="text" id="userInput" placeholder="" size="10">
<button onclick="getAnswer()">Submit Answer</button>
</form>

<p>Total Answered</p>
<p id="score"></p>
<p>Answered Correctly</p>
<p id="ans"></p>
<p>Your number grade</p>
<p id="percent">%</p>

</body>

</html>








var correct = 0,
wrong = 0,
ans,
firstnum = Math.floor(Math.random() * 10 + 1),
secondnum = Math.floor(Math.random() * 10 + 1),
total = firstnum + secondnum,
score,
input,
calc = "+";

function getMath() {

document.getElementById("firstnum").value = firstnum;
document.getElementById("secondnum").value = secondnum;
document.getElementById("calc").value = calc;
}

function getAnswer() {

var input = document.getElementById("userInput").value;
if (input == total) {
correct++;
} else {
wrong++;
}
result();
}


function result() {

score = correct + wrong;
percent = correct / score;
document.getElementById("score").innerHTML = score;
document.getElementById("ans").innerHTML = correct;
document.getElementById("percent").innerHTML = percent * 100;
getMath();
}

<body onload="getMath()">

<h1>Math Test</h1>

<input type="text" id="firstnum"></input>
<input type="text" id="calc">
<input type="text" id="secondnum">
<hr>

<form id="form1" onsubmit="return false">
<input type="text" id="userInput" placeholder="" size="10">
<button onclick="getAnswer()">Submit Answer</button>
</form>

<p>Total Answered</p>
<p id="score"></p>
<p>Answered Correctly</p>
<p id="ans"></p>
<p>Your number grade</p>
<p id="percent">%</p>

</body>

</html>





var correct = 0,
wrong = 0,
ans,
firstnum = Math.floor(Math.random() * 10 + 1),
secondnum = Math.floor(Math.random() * 10 + 1),
total = firstnum + secondnum,
score,
input,
calc = "+";

function getMath() {

document.getElementById("firstnum").value = firstnum;
document.getElementById("secondnum").value = secondnum;
document.getElementById("calc").value = calc;
}

function getAnswer() {

var input = document.getElementById("userInput").value;
if (input == total) {
correct++;
} else {
wrong++;
}
result();
}


function result() {

score = correct + wrong;
percent = correct / score;
document.getElementById("score").innerHTML = score;
document.getElementById("ans").innerHTML = correct;
document.getElementById("percent").innerHTML = percent * 100;
getMath();
}

<body onload="getMath()">

<h1>Math Test</h1>

<input type="text" id="firstnum"></input>
<input type="text" id="calc">
<input type="text" id="secondnum">
<hr>

<form id="form1" onsubmit="return false">
<input type="text" id="userInput" placeholder="" size="10">
<button onclick="getAnswer()">Submit Answer</button>
</form>

<p>Total Answered</p>
<p id="score"></p>
<p>Answered Correctly</p>
<p id="ans"></p>
<p>Your number grade</p>
<p id="percent">%</p>

</body>

</html>






javascript html function validation






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 25 '18 at 22:50









ksav

5,38721432




5,38721432










asked Nov 25 '18 at 22:36









Daryl KriefallDaryl Kriefall

154




154













  • Is placing a function at the end of result() not valid?

    – Daryl Kriefall
    Nov 25 '18 at 22:55











  • The math generation "getMath()" does not re-run at the end of the "result()" and I am not sure why. It looks like it is running once on load, and once again after submitting an answer.

    – ksav
    Nov 25 '18 at 22:57













  • Do you want to rerun getmath() when any of the values in firstnum, secondnum or calc are changed?

    – ksav
    Nov 25 '18 at 22:59











  • After calculating the user input and true/false, I want to generate a new set of numbers to calculate another user input.

    – Daryl Kriefall
    Nov 25 '18 at 23:13



















  • Is placing a function at the end of result() not valid?

    – Daryl Kriefall
    Nov 25 '18 at 22:55











  • The math generation "getMath()" does not re-run at the end of the "result()" and I am not sure why. It looks like it is running once on load, and once again after submitting an answer.

    – ksav
    Nov 25 '18 at 22:57













  • Do you want to rerun getmath() when any of the values in firstnum, secondnum or calc are changed?

    – ksav
    Nov 25 '18 at 22:59











  • After calculating the user input and true/false, I want to generate a new set of numbers to calculate another user input.

    – Daryl Kriefall
    Nov 25 '18 at 23:13

















Is placing a function at the end of result() not valid?

– Daryl Kriefall
Nov 25 '18 at 22:55





Is placing a function at the end of result() not valid?

– Daryl Kriefall
Nov 25 '18 at 22:55













The math generation "getMath()" does not re-run at the end of the "result()" and I am not sure why. It looks like it is running once on load, and once again after submitting an answer.

– ksav
Nov 25 '18 at 22:57







The math generation "getMath()" does not re-run at the end of the "result()" and I am not sure why. It looks like it is running once on load, and once again after submitting an answer.

– ksav
Nov 25 '18 at 22:57















Do you want to rerun getmath() when any of the values in firstnum, secondnum or calc are changed?

– ksav
Nov 25 '18 at 22:59





Do you want to rerun getmath() when any of the values in firstnum, secondnum or calc are changed?

– ksav
Nov 25 '18 at 22:59













After calculating the user input and true/false, I want to generate a new set of numbers to calculate another user input.

– Daryl Kriefall
Nov 25 '18 at 23:13





After calculating the user input and true/false, I want to generate a new set of numbers to calculate another user input.

– Daryl Kriefall
Nov 25 '18 at 23:13












2 Answers
2






active

oldest

votes


















1














Your second call to getMath runs, but it makes no difference on the page. That function does not pick new random values, but just redisplays what was already there... those random values were only generated once when the script loaded.



So move that randomising logic inside getMath. Also try to avoid too many global variables. If you would assign a new click handler to your button each time you generate a new math challenge, then you can in fact pass all necessary variables around and keep all the rest declared as local variables. Remove the onclick from the HTML part, and use code to set onclick.



Also change the input elements to span elements when the user is not supposed to change their content.



Here is how it could work:






window.onload = () => getMath(0, 0);

function getMath(correct, wrong) {
var firstnum = Math.floor(Math.random()*10+1),
secondnum = Math.floor(Math.random()*10+1),
calc = "+",
total = firstnum+secondnum;
document.getElementById("firstnum").textContent = firstnum;
document.getElementById("secondnum").textContent = secondnum;
document.getElementById("calc").textContent = calc;
document.getElementById("userInput").value = "";
document.getElementById("btnAnswer").onclick = () => getAnswer(total, correct || 0, wrong || 0);
}

function getAnswer(total, correct, wrong){
var input = document.getElementById("userInput").value;
if (input == total){
correct++;
} else{
wrong++;
}
result(correct, wrong);
}


function result(correct, wrong){
var score = correct+wrong;
var percent = correct/score;
document.getElementById("score").innerHTML = score;
document.getElementById("ans").innerHTML = correct;
document.getElementById("percent").innerHTML = percent*100;
getMath(correct, wrong);
}

<h1>Math Test</h1>

<span id="firstnum"> </span>
<span id="calc"> </span>
<span id="secondnum"> </span>
<hr>

<form id="form1" onsubmit="return false">
<input type="text" id="userInput" placeholder="" size="10">
<button id="btnAnswer">Submit Answer</button>
</form>

<p>Total Answered: <span id="score"></span></p>
<p>Answered Correctly: <span id="ans"></span></p>
<p>Your number grade: <span id="percent">%</span></p>








share|improve this answer


























  • I see that it works, But, I am trying to understand the syntax on the button function. I cant seem to connect the dots. I see the "for" loop but do not understand the target.

    – Daryl Kriefall
    Nov 26 '18 at 0:20






  • 1





    The button function is written as arrow function, the () is the function's empty argument list. You can also write it as a an inline function. What you prefer. There is no for loop.

    – trincot
    Nov 26 '18 at 6:09











  • Thank you for clarification. Your additions are quite effective.

    – Daryl Kriefall
    Nov 27 '18 at 3:56



















1














The reason why you weren't getting a second round of numbers is because the code that generates the random numbers wasn't inside of the getMath() function. The random number code only ran once, when the page first loads.



Now besides that, you have a lot of redundant/unneeded code (i.e. there is no need to keep track of how many wrong answers there are as long as we know how many questions were asked and how many you got correct) as well as many of your variables have names that don't accurately express what they contain.



Cleaning it all up, reduces the amount of code and the complexity of it as well.



See the inline comments for what changes were made:






// Do all your event binding in JavaScript, not with inline HTML event attributes:
window.addEventListener("DOMContentLoaded", populate);
document.querySelector("button").addEventListener("click", result);

// Declare and initialize all your variables.
var correct = 0;
var numQuestions = null;
var total = null;
var calc = "+";

// Get your DOM references just once and set your variable
// to the element itself, not a property of the element so
// that if you ever want to get a different property, you
// already have the DOM reference.
var firstNumElement = document.getElementById("firstnum");
var secondNumElement = document.getElementById("secondnum");
var calcElement = document.getElementById("calc");
var input = document.getElementById("userInput")
var numCorrectElement = document.getElementById("score");
var numQuestionsElement = document.getElementById("ans");
var percentElement = document.getElementById("percent");

function populate() {
// You need to generate new randoms after each successful guess
// so these lines need to be in a function that will be called again
firstNumElement.textContent = Math.floor(Math.random() * 10 + 1);
secondNumElement.textContent = Math.floor(Math.random() * 10 + 1);
calcElement.textContent = calc;
// prepending a "+" in front of the textContent converts it to a number
total = +firstNumElement.textContent + +secondNumElement.textContent;
numQuestions++; // Update how many questions have been asked
input.value = ""; // reset the user input
}

function result(){
// The getAnswer function should just be part of this function.
// We have a simple if/then here, so the JavaScript ternary syntax is easier:
correct = input.value == total ? correct + 1 : correct;

// Only use .innerHTML when the string has HTML in it that needs to be parsed.
// If not, use .textContent - it's faster and safer.
numCorrectElement.textContent = correct;
numQuestionsElement.textContent = numQuestions;
percentElement.textContent = (correct / numQuestions * 100).toFixed(2) + "%";
populate(); // Generate new randoms and update the page
}

<h1>Math Test</h1>

<!--
input elements don't have a closing tag
also, use type=number for numeric input
But here, since users won't be interacting
with this data, don't even use form fields.
-->
<span id="firstnum"></span>
<span type="text" id="calc"></span>
<span type="number" id="secondnum"></span>
<hr>

<!-- You're not submitting data anywhere, so you don't need a form element -->
<input type="number" id="userInput" size="10">
<button type="button">Submit Answer</button>

<p>Total Questions: <span id="ans"></span></p>
<p>Answered Correctly: <span id="score"></span></p>
<p>Your number grade: <span id="percent"></span></p>








share|improve this answer


























  • An abundance of useful tips. Thank you.

    – Daryl Kriefall
    Nov 26 '18 at 14:35











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53472712%2fhow-to-repeat-a-process-by-calling-a-function-in-javascript%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














Your second call to getMath runs, but it makes no difference on the page. That function does not pick new random values, but just redisplays what was already there... those random values were only generated once when the script loaded.



So move that randomising logic inside getMath. Also try to avoid too many global variables. If you would assign a new click handler to your button each time you generate a new math challenge, then you can in fact pass all necessary variables around and keep all the rest declared as local variables. Remove the onclick from the HTML part, and use code to set onclick.



Also change the input elements to span elements when the user is not supposed to change their content.



Here is how it could work:






window.onload = () => getMath(0, 0);

function getMath(correct, wrong) {
var firstnum = Math.floor(Math.random()*10+1),
secondnum = Math.floor(Math.random()*10+1),
calc = "+",
total = firstnum+secondnum;
document.getElementById("firstnum").textContent = firstnum;
document.getElementById("secondnum").textContent = secondnum;
document.getElementById("calc").textContent = calc;
document.getElementById("userInput").value = "";
document.getElementById("btnAnswer").onclick = () => getAnswer(total, correct || 0, wrong || 0);
}

function getAnswer(total, correct, wrong){
var input = document.getElementById("userInput").value;
if (input == total){
correct++;
} else{
wrong++;
}
result(correct, wrong);
}


function result(correct, wrong){
var score = correct+wrong;
var percent = correct/score;
document.getElementById("score").innerHTML = score;
document.getElementById("ans").innerHTML = correct;
document.getElementById("percent").innerHTML = percent*100;
getMath(correct, wrong);
}

<h1>Math Test</h1>

<span id="firstnum"> </span>
<span id="calc"> </span>
<span id="secondnum"> </span>
<hr>

<form id="form1" onsubmit="return false">
<input type="text" id="userInput" placeholder="" size="10">
<button id="btnAnswer">Submit Answer</button>
</form>

<p>Total Answered: <span id="score"></span></p>
<p>Answered Correctly: <span id="ans"></span></p>
<p>Your number grade: <span id="percent">%</span></p>








share|improve this answer


























  • I see that it works, But, I am trying to understand the syntax on the button function. I cant seem to connect the dots. I see the "for" loop but do not understand the target.

    – Daryl Kriefall
    Nov 26 '18 at 0:20






  • 1





    The button function is written as arrow function, the () is the function's empty argument list. You can also write it as a an inline function. What you prefer. There is no for loop.

    – trincot
    Nov 26 '18 at 6:09











  • Thank you for clarification. Your additions are quite effective.

    – Daryl Kriefall
    Nov 27 '18 at 3:56
















1














Your second call to getMath runs, but it makes no difference on the page. That function does not pick new random values, but just redisplays what was already there... those random values were only generated once when the script loaded.



So move that randomising logic inside getMath. Also try to avoid too many global variables. If you would assign a new click handler to your button each time you generate a new math challenge, then you can in fact pass all necessary variables around and keep all the rest declared as local variables. Remove the onclick from the HTML part, and use code to set onclick.



Also change the input elements to span elements when the user is not supposed to change their content.



Here is how it could work:






window.onload = () => getMath(0, 0);

function getMath(correct, wrong) {
var firstnum = Math.floor(Math.random()*10+1),
secondnum = Math.floor(Math.random()*10+1),
calc = "+",
total = firstnum+secondnum;
document.getElementById("firstnum").textContent = firstnum;
document.getElementById("secondnum").textContent = secondnum;
document.getElementById("calc").textContent = calc;
document.getElementById("userInput").value = "";
document.getElementById("btnAnswer").onclick = () => getAnswer(total, correct || 0, wrong || 0);
}

function getAnswer(total, correct, wrong){
var input = document.getElementById("userInput").value;
if (input == total){
correct++;
} else{
wrong++;
}
result(correct, wrong);
}


function result(correct, wrong){
var score = correct+wrong;
var percent = correct/score;
document.getElementById("score").innerHTML = score;
document.getElementById("ans").innerHTML = correct;
document.getElementById("percent").innerHTML = percent*100;
getMath(correct, wrong);
}

<h1>Math Test</h1>

<span id="firstnum"> </span>
<span id="calc"> </span>
<span id="secondnum"> </span>
<hr>

<form id="form1" onsubmit="return false">
<input type="text" id="userInput" placeholder="" size="10">
<button id="btnAnswer">Submit Answer</button>
</form>

<p>Total Answered: <span id="score"></span></p>
<p>Answered Correctly: <span id="ans"></span></p>
<p>Your number grade: <span id="percent">%</span></p>








share|improve this answer


























  • I see that it works, But, I am trying to understand the syntax on the button function. I cant seem to connect the dots. I see the "for" loop but do not understand the target.

    – Daryl Kriefall
    Nov 26 '18 at 0:20






  • 1





    The button function is written as arrow function, the () is the function's empty argument list. You can also write it as a an inline function. What you prefer. There is no for loop.

    – trincot
    Nov 26 '18 at 6:09











  • Thank you for clarification. Your additions are quite effective.

    – Daryl Kriefall
    Nov 27 '18 at 3:56














1












1








1







Your second call to getMath runs, but it makes no difference on the page. That function does not pick new random values, but just redisplays what was already there... those random values were only generated once when the script loaded.



So move that randomising logic inside getMath. Also try to avoid too many global variables. If you would assign a new click handler to your button each time you generate a new math challenge, then you can in fact pass all necessary variables around and keep all the rest declared as local variables. Remove the onclick from the HTML part, and use code to set onclick.



Also change the input elements to span elements when the user is not supposed to change their content.



Here is how it could work:






window.onload = () => getMath(0, 0);

function getMath(correct, wrong) {
var firstnum = Math.floor(Math.random()*10+1),
secondnum = Math.floor(Math.random()*10+1),
calc = "+",
total = firstnum+secondnum;
document.getElementById("firstnum").textContent = firstnum;
document.getElementById("secondnum").textContent = secondnum;
document.getElementById("calc").textContent = calc;
document.getElementById("userInput").value = "";
document.getElementById("btnAnswer").onclick = () => getAnswer(total, correct || 0, wrong || 0);
}

function getAnswer(total, correct, wrong){
var input = document.getElementById("userInput").value;
if (input == total){
correct++;
} else{
wrong++;
}
result(correct, wrong);
}


function result(correct, wrong){
var score = correct+wrong;
var percent = correct/score;
document.getElementById("score").innerHTML = score;
document.getElementById("ans").innerHTML = correct;
document.getElementById("percent").innerHTML = percent*100;
getMath(correct, wrong);
}

<h1>Math Test</h1>

<span id="firstnum"> </span>
<span id="calc"> </span>
<span id="secondnum"> </span>
<hr>

<form id="form1" onsubmit="return false">
<input type="text" id="userInput" placeholder="" size="10">
<button id="btnAnswer">Submit Answer</button>
</form>

<p>Total Answered: <span id="score"></span></p>
<p>Answered Correctly: <span id="ans"></span></p>
<p>Your number grade: <span id="percent">%</span></p>








share|improve this answer















Your second call to getMath runs, but it makes no difference on the page. That function does not pick new random values, but just redisplays what was already there... those random values were only generated once when the script loaded.



So move that randomising logic inside getMath. Also try to avoid too many global variables. If you would assign a new click handler to your button each time you generate a new math challenge, then you can in fact pass all necessary variables around and keep all the rest declared as local variables. Remove the onclick from the HTML part, and use code to set onclick.



Also change the input elements to span elements when the user is not supposed to change their content.



Here is how it could work:






window.onload = () => getMath(0, 0);

function getMath(correct, wrong) {
var firstnum = Math.floor(Math.random()*10+1),
secondnum = Math.floor(Math.random()*10+1),
calc = "+",
total = firstnum+secondnum;
document.getElementById("firstnum").textContent = firstnum;
document.getElementById("secondnum").textContent = secondnum;
document.getElementById("calc").textContent = calc;
document.getElementById("userInput").value = "";
document.getElementById("btnAnswer").onclick = () => getAnswer(total, correct || 0, wrong || 0);
}

function getAnswer(total, correct, wrong){
var input = document.getElementById("userInput").value;
if (input == total){
correct++;
} else{
wrong++;
}
result(correct, wrong);
}


function result(correct, wrong){
var score = correct+wrong;
var percent = correct/score;
document.getElementById("score").innerHTML = score;
document.getElementById("ans").innerHTML = correct;
document.getElementById("percent").innerHTML = percent*100;
getMath(correct, wrong);
}

<h1>Math Test</h1>

<span id="firstnum"> </span>
<span id="calc"> </span>
<span id="secondnum"> </span>
<hr>

<form id="form1" onsubmit="return false">
<input type="text" id="userInput" placeholder="" size="10">
<button id="btnAnswer">Submit Answer</button>
</form>

<p>Total Answered: <span id="score"></span></p>
<p>Answered Correctly: <span id="ans"></span></p>
<p>Your number grade: <span id="percent">%</span></p>








window.onload = () => getMath(0, 0);

function getMath(correct, wrong) {
var firstnum = Math.floor(Math.random()*10+1),
secondnum = Math.floor(Math.random()*10+1),
calc = "+",
total = firstnum+secondnum;
document.getElementById("firstnum").textContent = firstnum;
document.getElementById("secondnum").textContent = secondnum;
document.getElementById("calc").textContent = calc;
document.getElementById("userInput").value = "";
document.getElementById("btnAnswer").onclick = () => getAnswer(total, correct || 0, wrong || 0);
}

function getAnswer(total, correct, wrong){
var input = document.getElementById("userInput").value;
if (input == total){
correct++;
} else{
wrong++;
}
result(correct, wrong);
}


function result(correct, wrong){
var score = correct+wrong;
var percent = correct/score;
document.getElementById("score").innerHTML = score;
document.getElementById("ans").innerHTML = correct;
document.getElementById("percent").innerHTML = percent*100;
getMath(correct, wrong);
}

<h1>Math Test</h1>

<span id="firstnum"> </span>
<span id="calc"> </span>
<span id="secondnum"> </span>
<hr>

<form id="form1" onsubmit="return false">
<input type="text" id="userInput" placeholder="" size="10">
<button id="btnAnswer">Submit Answer</button>
</form>

<p>Total Answered: <span id="score"></span></p>
<p>Answered Correctly: <span id="ans"></span></p>
<p>Your number grade: <span id="percent">%</span></p>





window.onload = () => getMath(0, 0);

function getMath(correct, wrong) {
var firstnum = Math.floor(Math.random()*10+1),
secondnum = Math.floor(Math.random()*10+1),
calc = "+",
total = firstnum+secondnum;
document.getElementById("firstnum").textContent = firstnum;
document.getElementById("secondnum").textContent = secondnum;
document.getElementById("calc").textContent = calc;
document.getElementById("userInput").value = "";
document.getElementById("btnAnswer").onclick = () => getAnswer(total, correct || 0, wrong || 0);
}

function getAnswer(total, correct, wrong){
var input = document.getElementById("userInput").value;
if (input == total){
correct++;
} else{
wrong++;
}
result(correct, wrong);
}


function result(correct, wrong){
var score = correct+wrong;
var percent = correct/score;
document.getElementById("score").innerHTML = score;
document.getElementById("ans").innerHTML = correct;
document.getElementById("percent").innerHTML = percent*100;
getMath(correct, wrong);
}

<h1>Math Test</h1>

<span id="firstnum"> </span>
<span id="calc"> </span>
<span id="secondnum"> </span>
<hr>

<form id="form1" onsubmit="return false">
<input type="text" id="userInput" placeholder="" size="10">
<button id="btnAnswer">Submit Answer</button>
</form>

<p>Total Answered: <span id="score"></span></p>
<p>Answered Correctly: <span id="ans"></span></p>
<p>Your number grade: <span id="percent">%</span></p>






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 25 '18 at 23:06

























answered Nov 25 '18 at 23:01









trincottrincot

128k1689123




128k1689123













  • I see that it works, But, I am trying to understand the syntax on the button function. I cant seem to connect the dots. I see the "for" loop but do not understand the target.

    – Daryl Kriefall
    Nov 26 '18 at 0:20






  • 1





    The button function is written as arrow function, the () is the function's empty argument list. You can also write it as a an inline function. What you prefer. There is no for loop.

    – trincot
    Nov 26 '18 at 6:09











  • Thank you for clarification. Your additions are quite effective.

    – Daryl Kriefall
    Nov 27 '18 at 3:56



















  • I see that it works, But, I am trying to understand the syntax on the button function. I cant seem to connect the dots. I see the "for" loop but do not understand the target.

    – Daryl Kriefall
    Nov 26 '18 at 0:20






  • 1





    The button function is written as arrow function, the () is the function's empty argument list. You can also write it as a an inline function. What you prefer. There is no for loop.

    – trincot
    Nov 26 '18 at 6:09











  • Thank you for clarification. Your additions are quite effective.

    – Daryl Kriefall
    Nov 27 '18 at 3:56

















I see that it works, But, I am trying to understand the syntax on the button function. I cant seem to connect the dots. I see the "for" loop but do not understand the target.

– Daryl Kriefall
Nov 26 '18 at 0:20





I see that it works, But, I am trying to understand the syntax on the button function. I cant seem to connect the dots. I see the "for" loop but do not understand the target.

– Daryl Kriefall
Nov 26 '18 at 0:20




1




1





The button function is written as arrow function, the () is the function's empty argument list. You can also write it as a an inline function. What you prefer. There is no for loop.

– trincot
Nov 26 '18 at 6:09





The button function is written as arrow function, the () is the function's empty argument list. You can also write it as a an inline function. What you prefer. There is no for loop.

– trincot
Nov 26 '18 at 6:09













Thank you for clarification. Your additions are quite effective.

– Daryl Kriefall
Nov 27 '18 at 3:56





Thank you for clarification. Your additions are quite effective.

– Daryl Kriefall
Nov 27 '18 at 3:56













1














The reason why you weren't getting a second round of numbers is because the code that generates the random numbers wasn't inside of the getMath() function. The random number code only ran once, when the page first loads.



Now besides that, you have a lot of redundant/unneeded code (i.e. there is no need to keep track of how many wrong answers there are as long as we know how many questions were asked and how many you got correct) as well as many of your variables have names that don't accurately express what they contain.



Cleaning it all up, reduces the amount of code and the complexity of it as well.



See the inline comments for what changes were made:






// Do all your event binding in JavaScript, not with inline HTML event attributes:
window.addEventListener("DOMContentLoaded", populate);
document.querySelector("button").addEventListener("click", result);

// Declare and initialize all your variables.
var correct = 0;
var numQuestions = null;
var total = null;
var calc = "+";

// Get your DOM references just once and set your variable
// to the element itself, not a property of the element so
// that if you ever want to get a different property, you
// already have the DOM reference.
var firstNumElement = document.getElementById("firstnum");
var secondNumElement = document.getElementById("secondnum");
var calcElement = document.getElementById("calc");
var input = document.getElementById("userInput")
var numCorrectElement = document.getElementById("score");
var numQuestionsElement = document.getElementById("ans");
var percentElement = document.getElementById("percent");

function populate() {
// You need to generate new randoms after each successful guess
// so these lines need to be in a function that will be called again
firstNumElement.textContent = Math.floor(Math.random() * 10 + 1);
secondNumElement.textContent = Math.floor(Math.random() * 10 + 1);
calcElement.textContent = calc;
// prepending a "+" in front of the textContent converts it to a number
total = +firstNumElement.textContent + +secondNumElement.textContent;
numQuestions++; // Update how many questions have been asked
input.value = ""; // reset the user input
}

function result(){
// The getAnswer function should just be part of this function.
// We have a simple if/then here, so the JavaScript ternary syntax is easier:
correct = input.value == total ? correct + 1 : correct;

// Only use .innerHTML when the string has HTML in it that needs to be parsed.
// If not, use .textContent - it's faster and safer.
numCorrectElement.textContent = correct;
numQuestionsElement.textContent = numQuestions;
percentElement.textContent = (correct / numQuestions * 100).toFixed(2) + "%";
populate(); // Generate new randoms and update the page
}

<h1>Math Test</h1>

<!--
input elements don't have a closing tag
also, use type=number for numeric input
But here, since users won't be interacting
with this data, don't even use form fields.
-->
<span id="firstnum"></span>
<span type="text" id="calc"></span>
<span type="number" id="secondnum"></span>
<hr>

<!-- You're not submitting data anywhere, so you don't need a form element -->
<input type="number" id="userInput" size="10">
<button type="button">Submit Answer</button>

<p>Total Questions: <span id="ans"></span></p>
<p>Answered Correctly: <span id="score"></span></p>
<p>Your number grade: <span id="percent"></span></p>








share|improve this answer


























  • An abundance of useful tips. Thank you.

    – Daryl Kriefall
    Nov 26 '18 at 14:35
















1














The reason why you weren't getting a second round of numbers is because the code that generates the random numbers wasn't inside of the getMath() function. The random number code only ran once, when the page first loads.



Now besides that, you have a lot of redundant/unneeded code (i.e. there is no need to keep track of how many wrong answers there are as long as we know how many questions were asked and how many you got correct) as well as many of your variables have names that don't accurately express what they contain.



Cleaning it all up, reduces the amount of code and the complexity of it as well.



See the inline comments for what changes were made:






// Do all your event binding in JavaScript, not with inline HTML event attributes:
window.addEventListener("DOMContentLoaded", populate);
document.querySelector("button").addEventListener("click", result);

// Declare and initialize all your variables.
var correct = 0;
var numQuestions = null;
var total = null;
var calc = "+";

// Get your DOM references just once and set your variable
// to the element itself, not a property of the element so
// that if you ever want to get a different property, you
// already have the DOM reference.
var firstNumElement = document.getElementById("firstnum");
var secondNumElement = document.getElementById("secondnum");
var calcElement = document.getElementById("calc");
var input = document.getElementById("userInput")
var numCorrectElement = document.getElementById("score");
var numQuestionsElement = document.getElementById("ans");
var percentElement = document.getElementById("percent");

function populate() {
// You need to generate new randoms after each successful guess
// so these lines need to be in a function that will be called again
firstNumElement.textContent = Math.floor(Math.random() * 10 + 1);
secondNumElement.textContent = Math.floor(Math.random() * 10 + 1);
calcElement.textContent = calc;
// prepending a "+" in front of the textContent converts it to a number
total = +firstNumElement.textContent + +secondNumElement.textContent;
numQuestions++; // Update how many questions have been asked
input.value = ""; // reset the user input
}

function result(){
// The getAnswer function should just be part of this function.
// We have a simple if/then here, so the JavaScript ternary syntax is easier:
correct = input.value == total ? correct + 1 : correct;

// Only use .innerHTML when the string has HTML in it that needs to be parsed.
// If not, use .textContent - it's faster and safer.
numCorrectElement.textContent = correct;
numQuestionsElement.textContent = numQuestions;
percentElement.textContent = (correct / numQuestions * 100).toFixed(2) + "%";
populate(); // Generate new randoms and update the page
}

<h1>Math Test</h1>

<!--
input elements don't have a closing tag
also, use type=number for numeric input
But here, since users won't be interacting
with this data, don't even use form fields.
-->
<span id="firstnum"></span>
<span type="text" id="calc"></span>
<span type="number" id="secondnum"></span>
<hr>

<!-- You're not submitting data anywhere, so you don't need a form element -->
<input type="number" id="userInput" size="10">
<button type="button">Submit Answer</button>

<p>Total Questions: <span id="ans"></span></p>
<p>Answered Correctly: <span id="score"></span></p>
<p>Your number grade: <span id="percent"></span></p>








share|improve this answer


























  • An abundance of useful tips. Thank you.

    – Daryl Kriefall
    Nov 26 '18 at 14:35














1












1








1







The reason why you weren't getting a second round of numbers is because the code that generates the random numbers wasn't inside of the getMath() function. The random number code only ran once, when the page first loads.



Now besides that, you have a lot of redundant/unneeded code (i.e. there is no need to keep track of how many wrong answers there are as long as we know how many questions were asked and how many you got correct) as well as many of your variables have names that don't accurately express what they contain.



Cleaning it all up, reduces the amount of code and the complexity of it as well.



See the inline comments for what changes were made:






// Do all your event binding in JavaScript, not with inline HTML event attributes:
window.addEventListener("DOMContentLoaded", populate);
document.querySelector("button").addEventListener("click", result);

// Declare and initialize all your variables.
var correct = 0;
var numQuestions = null;
var total = null;
var calc = "+";

// Get your DOM references just once and set your variable
// to the element itself, not a property of the element so
// that if you ever want to get a different property, you
// already have the DOM reference.
var firstNumElement = document.getElementById("firstnum");
var secondNumElement = document.getElementById("secondnum");
var calcElement = document.getElementById("calc");
var input = document.getElementById("userInput")
var numCorrectElement = document.getElementById("score");
var numQuestionsElement = document.getElementById("ans");
var percentElement = document.getElementById("percent");

function populate() {
// You need to generate new randoms after each successful guess
// so these lines need to be in a function that will be called again
firstNumElement.textContent = Math.floor(Math.random() * 10 + 1);
secondNumElement.textContent = Math.floor(Math.random() * 10 + 1);
calcElement.textContent = calc;
// prepending a "+" in front of the textContent converts it to a number
total = +firstNumElement.textContent + +secondNumElement.textContent;
numQuestions++; // Update how many questions have been asked
input.value = ""; // reset the user input
}

function result(){
// The getAnswer function should just be part of this function.
// We have a simple if/then here, so the JavaScript ternary syntax is easier:
correct = input.value == total ? correct + 1 : correct;

// Only use .innerHTML when the string has HTML in it that needs to be parsed.
// If not, use .textContent - it's faster and safer.
numCorrectElement.textContent = correct;
numQuestionsElement.textContent = numQuestions;
percentElement.textContent = (correct / numQuestions * 100).toFixed(2) + "%";
populate(); // Generate new randoms and update the page
}

<h1>Math Test</h1>

<!--
input elements don't have a closing tag
also, use type=number for numeric input
But here, since users won't be interacting
with this data, don't even use form fields.
-->
<span id="firstnum"></span>
<span type="text" id="calc"></span>
<span type="number" id="secondnum"></span>
<hr>

<!-- You're not submitting data anywhere, so you don't need a form element -->
<input type="number" id="userInput" size="10">
<button type="button">Submit Answer</button>

<p>Total Questions: <span id="ans"></span></p>
<p>Answered Correctly: <span id="score"></span></p>
<p>Your number grade: <span id="percent"></span></p>








share|improve this answer















The reason why you weren't getting a second round of numbers is because the code that generates the random numbers wasn't inside of the getMath() function. The random number code only ran once, when the page first loads.



Now besides that, you have a lot of redundant/unneeded code (i.e. there is no need to keep track of how many wrong answers there are as long as we know how many questions were asked and how many you got correct) as well as many of your variables have names that don't accurately express what they contain.



Cleaning it all up, reduces the amount of code and the complexity of it as well.



See the inline comments for what changes were made:






// Do all your event binding in JavaScript, not with inline HTML event attributes:
window.addEventListener("DOMContentLoaded", populate);
document.querySelector("button").addEventListener("click", result);

// Declare and initialize all your variables.
var correct = 0;
var numQuestions = null;
var total = null;
var calc = "+";

// Get your DOM references just once and set your variable
// to the element itself, not a property of the element so
// that if you ever want to get a different property, you
// already have the DOM reference.
var firstNumElement = document.getElementById("firstnum");
var secondNumElement = document.getElementById("secondnum");
var calcElement = document.getElementById("calc");
var input = document.getElementById("userInput")
var numCorrectElement = document.getElementById("score");
var numQuestionsElement = document.getElementById("ans");
var percentElement = document.getElementById("percent");

function populate() {
// You need to generate new randoms after each successful guess
// so these lines need to be in a function that will be called again
firstNumElement.textContent = Math.floor(Math.random() * 10 + 1);
secondNumElement.textContent = Math.floor(Math.random() * 10 + 1);
calcElement.textContent = calc;
// prepending a "+" in front of the textContent converts it to a number
total = +firstNumElement.textContent + +secondNumElement.textContent;
numQuestions++; // Update how many questions have been asked
input.value = ""; // reset the user input
}

function result(){
// The getAnswer function should just be part of this function.
// We have a simple if/then here, so the JavaScript ternary syntax is easier:
correct = input.value == total ? correct + 1 : correct;

// Only use .innerHTML when the string has HTML in it that needs to be parsed.
// If not, use .textContent - it's faster and safer.
numCorrectElement.textContent = correct;
numQuestionsElement.textContent = numQuestions;
percentElement.textContent = (correct / numQuestions * 100).toFixed(2) + "%";
populate(); // Generate new randoms and update the page
}

<h1>Math Test</h1>

<!--
input elements don't have a closing tag
also, use type=number for numeric input
But here, since users won't be interacting
with this data, don't even use form fields.
-->
<span id="firstnum"></span>
<span type="text" id="calc"></span>
<span type="number" id="secondnum"></span>
<hr>

<!-- You're not submitting data anywhere, so you don't need a form element -->
<input type="number" id="userInput" size="10">
<button type="button">Submit Answer</button>

<p>Total Questions: <span id="ans"></span></p>
<p>Answered Correctly: <span id="score"></span></p>
<p>Your number grade: <span id="percent"></span></p>








// Do all your event binding in JavaScript, not with inline HTML event attributes:
window.addEventListener("DOMContentLoaded", populate);
document.querySelector("button").addEventListener("click", result);

// Declare and initialize all your variables.
var correct = 0;
var numQuestions = null;
var total = null;
var calc = "+";

// Get your DOM references just once and set your variable
// to the element itself, not a property of the element so
// that if you ever want to get a different property, you
// already have the DOM reference.
var firstNumElement = document.getElementById("firstnum");
var secondNumElement = document.getElementById("secondnum");
var calcElement = document.getElementById("calc");
var input = document.getElementById("userInput")
var numCorrectElement = document.getElementById("score");
var numQuestionsElement = document.getElementById("ans");
var percentElement = document.getElementById("percent");

function populate() {
// You need to generate new randoms after each successful guess
// so these lines need to be in a function that will be called again
firstNumElement.textContent = Math.floor(Math.random() * 10 + 1);
secondNumElement.textContent = Math.floor(Math.random() * 10 + 1);
calcElement.textContent = calc;
// prepending a "+" in front of the textContent converts it to a number
total = +firstNumElement.textContent + +secondNumElement.textContent;
numQuestions++; // Update how many questions have been asked
input.value = ""; // reset the user input
}

function result(){
// The getAnswer function should just be part of this function.
// We have a simple if/then here, so the JavaScript ternary syntax is easier:
correct = input.value == total ? correct + 1 : correct;

// Only use .innerHTML when the string has HTML in it that needs to be parsed.
// If not, use .textContent - it's faster and safer.
numCorrectElement.textContent = correct;
numQuestionsElement.textContent = numQuestions;
percentElement.textContent = (correct / numQuestions * 100).toFixed(2) + "%";
populate(); // Generate new randoms and update the page
}

<h1>Math Test</h1>

<!--
input elements don't have a closing tag
also, use type=number for numeric input
But here, since users won't be interacting
with this data, don't even use form fields.
-->
<span id="firstnum"></span>
<span type="text" id="calc"></span>
<span type="number" id="secondnum"></span>
<hr>

<!-- You're not submitting data anywhere, so you don't need a form element -->
<input type="number" id="userInput" size="10">
<button type="button">Submit Answer</button>

<p>Total Questions: <span id="ans"></span></p>
<p>Answered Correctly: <span id="score"></span></p>
<p>Your number grade: <span id="percent"></span></p>





// Do all your event binding in JavaScript, not with inline HTML event attributes:
window.addEventListener("DOMContentLoaded", populate);
document.querySelector("button").addEventListener("click", result);

// Declare and initialize all your variables.
var correct = 0;
var numQuestions = null;
var total = null;
var calc = "+";

// Get your DOM references just once and set your variable
// to the element itself, not a property of the element so
// that if you ever want to get a different property, you
// already have the DOM reference.
var firstNumElement = document.getElementById("firstnum");
var secondNumElement = document.getElementById("secondnum");
var calcElement = document.getElementById("calc");
var input = document.getElementById("userInput")
var numCorrectElement = document.getElementById("score");
var numQuestionsElement = document.getElementById("ans");
var percentElement = document.getElementById("percent");

function populate() {
// You need to generate new randoms after each successful guess
// so these lines need to be in a function that will be called again
firstNumElement.textContent = Math.floor(Math.random() * 10 + 1);
secondNumElement.textContent = Math.floor(Math.random() * 10 + 1);
calcElement.textContent = calc;
// prepending a "+" in front of the textContent converts it to a number
total = +firstNumElement.textContent + +secondNumElement.textContent;
numQuestions++; // Update how many questions have been asked
input.value = ""; // reset the user input
}

function result(){
// The getAnswer function should just be part of this function.
// We have a simple if/then here, so the JavaScript ternary syntax is easier:
correct = input.value == total ? correct + 1 : correct;

// Only use .innerHTML when the string has HTML in it that needs to be parsed.
// If not, use .textContent - it's faster and safer.
numCorrectElement.textContent = correct;
numQuestionsElement.textContent = numQuestions;
percentElement.textContent = (correct / numQuestions * 100).toFixed(2) + "%";
populate(); // Generate new randoms and update the page
}

<h1>Math Test</h1>

<!--
input elements don't have a closing tag
also, use type=number for numeric input
But here, since users won't be interacting
with this data, don't even use form fields.
-->
<span id="firstnum"></span>
<span type="text" id="calc"></span>
<span type="number" id="secondnum"></span>
<hr>

<!-- You're not submitting data anywhere, so you don't need a form element -->
<input type="number" id="userInput" size="10">
<button type="button">Submit Answer</button>

<p>Total Questions: <span id="ans"></span></p>
<p>Answered Correctly: <span id="score"></span></p>
<p>Your number grade: <span id="percent"></span></p>






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 26 '18 at 15:23

























answered Nov 25 '18 at 23:22









Scott MarcusScott Marcus

39.8k52040




39.8k52040













  • An abundance of useful tips. Thank you.

    – Daryl Kriefall
    Nov 26 '18 at 14:35



















  • An abundance of useful tips. Thank you.

    – Daryl Kriefall
    Nov 26 '18 at 14:35

















An abundance of useful tips. Thank you.

– Daryl Kriefall
Nov 26 '18 at 14:35





An abundance of useful tips. Thank you.

– Daryl Kriefall
Nov 26 '18 at 14:35


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53472712%2fhow-to-repeat-a-process-by-calling-a-function-in-javascript%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Costa Masnaga

Fotorealismo

Sidney Franklin