Edwin Edwin - 7 months ago 10
Javascript Question

What's the best way to get the input of a text box if the function grabbing the input is already called?

The title might be hard to understand, so I'll explain it here.

I have a function called addition, which gives problems to the user. It displays questions like "4+5", and to evaluate the answer, I have an input box.

The addition function is already called, but how could I get the value of the answer in the text box? I tried using jQuery to listen to the enter button, but I'm not sure how I could relay that information (the answer) back to the other addition function.

Here is an example of what it looks like:

enter image description here

Here is some of the code I'm using:

<input class="answer" id="input" type="text">


JS:

function addition() { //addition function



for(i=cookiearray[1]; i>0;i--) { //uses cookies from previous page

var n1= Math.floor(Math.random() * (cookiearray[3] - cookiearray[2]) + cookiearray[2]); //creates cookie

//random number between user's min and max
var n2= Math.floor(Math.random() * (cookiearray[3] - cookiearray[2]) + cookiearray[2]);

document.getElementById("question").innerHTML = n1 + "+" + n2 + "=" ; //displays to page

Dan Dan
Answer

You can also look for an ENTER key press and then check the current focused element. But for now - just have them click a button when they want to check their answer:

$(document).ready(function(){
   $('#myBtn').click(function(){
      if(calculatedAnswer == $('myInput').val()){
         //correct answer
      } else {
         //incorrect answer
      }
   });
})

and if you know what question you are asking - you can just calculate it on the fly?

$(document).ready(function(){
   $('#myBtn').click(function(){
      var question_id = document.getActiveElement.id //something to this effect
      var calculatedAnswer = calculate_answer(question_id);
      if(calculatedAnswer == $('myInput').val()){
         //correct answer
      } else {
         //incorrect answer
      }
   });
})
Comments