javascripthtmlfunctionmathfeedback

How to create a function that reacts to what a previous function generated in Javascript


var operators = ['+','-'];

function F1()
{    
  	Z1 = document.getElementById("Z1");
    	Z2 = document.getElementById("Z2");
    	oper=document.getElementById("operator");
    	answer=document.getElementById("answer");
    	
        rZ1 = Math.floor((Math.random()*10));
    	rZ2 = Math.floor((Math.random()*10)+1);
    	op = operators[Math.floor(Math.random()*2)];
   		
        Z1.innerHTML=rZ1;
    	Z2.innerHTML=rZ2;
    	oper.innerHTML=op;
    	answer.innerHTML = eval(rZ1 + op + rZ2);      
}

document.getElementById("button2").addEventListener("click", F2);

function F2()
{
	antw = parseInt(document.getElementById("userAnswer").value, 10);
	feedBack = document.getElementById("feedBack");
	ant = document.getElementById("answer");

	{
	if(antw == ant) {
	feedBack.textContent = "right";

	} else {
	feedBack.textContent = "wrong";
	}
} 	
};
<button onclick="F1()"> New </button>

<p> 
    	<label id="Z1"> </label> 
    	<label id="operator"> </label>
   	<label id="Z2"> </label>
      = <input id = "userAnswer" type=text>
        <button id = "button2" >answer</button>
</p>   

<p id = "feedBack"> </p>

<p><label id="answer"> </label></p>


Solution

  • You can call F2 at the end of the function F1 and pass the answer to F2 as a parameter.

    function F2(answer){
        //logic to check answer
        return feedback
    }
    
    function F1(){
       //logic to calculate answer
       F2(answer)
    }
    

    You can use your original code, only need to fix a small problem in your code. You forgot to use textContent to get the value from your html, so you are comparing undefined value with your answer

    ant = document.getElementById("answer").textContent;