从提示框调用函数

时间:2017-02-07 07:43:18

标签: javascript

我有一个提示框,并且给定条件,我希望在返回提示值时调用checkNumbers函数,但我不确定如何传递该值。

function getNumbersMakeProblem() {

  // a, b are declared up here usually
  userAnswer = prompt("State the value of the unknown variable in the \
  following problem below. If your answer is not an integer, round to the \
  nearest hundredth. " + a + "x - " + b + " = " + 3*a);

  return userAnswer()
}

function checkAnswer(a, b, userAnswer) {

  var numAndDenom = userAnswer.split('/'),
      result = parseInt(numAndDenom[0], 10) / parseInt(numAndDenom[1], 10),
      resultToHundreth = Number(result.toFixed(2)),
      correctAnswer = ((3 * Number(b)) / Number(a));

  if (Number(userAnswer) === correctAnswer) {
    alert("CORRECT!!!");
  }
  // Further Conditions
}

1 个答案:

答案 0 :(得分:1)

<input type="text" id="input_a">
<input type="text" id="input_b">
<input type="button" value="Run" onclick="getNumbersMakeProblem();">

//script tag here
function getNumbersMakeProblem(){
   var a = document.getElementById("input_a").value,
   a = a.toLowerCase();

   var b = document.getElementById("input_b").value;

//variables a and b are the users input for their birth month and day respectively

if (a === "january") {
  a = 1;
}

// leaving other months out to save space

if (a === "december") {
  a = 12;
}   
var userAnswer = prompt("State the value of the unknown variable in the \
following problem below. If your answer is not an integer, round to the \
nearest hundredth. " + a + "x - " + b + " = " + 3*a);


checkAnswer(a,b,userAnswer); // Single change here
}



// IDK how to incorporate this second piece after the first prompt 

function checkAnswer(a, b, userAnswer) {

  var numAndDenom = userAnswer.split('/')
  var result = parseInt(numAndDenom[0], 10) / parseInt(numAndDenom[1], 10);
  var resultToHundreth = Number(result.toFixed(2));
  var correctAnswer = ((3*Number(a) + Number(b))/Number(a));

  if (Number(userAnswer) === correctAnswer) {
    alert("CORRECT!!!");
  }
  else if (userAnswer === correctAnswer.toFixed(2)) {
    alert("AWESOME!!!");
  } 
  else if(userAnswer === correctAnswer.toFixed(1)) {
    alert("You were supposed to round to the nearest HUNDRETH.")
  }
  else if (Number(result) === correctAnswer) {
    alert("Now convert your answer to a decimal.")
  }
  else {
    alert("TRY AGAIN..."); }

  } 
// closing script tag here