0

I'm trying to get the <h4> tag to update if a different button is pressed, but it doesn't change. I want the two functions to rerun every time I click a button.

function submit(clicked_id) {
  var answer = document.getElementById(clicked_id).innerHTML;
  answercheck()
}

function answercheck() {
  if (answer != "George Washington") {
    document.getElementById("answer").innerHTML = "You are incorrect.";
  } else {
    document.getElementById("answer").innerHTML = "You are correct!";
  }
}
<h1>Quiz</h1>
<h3>Who is the first president of the United States?</h3>
<button onclick="submit(this.id);" id="ans1">Benjamin Franklin</button>
<button onclick="submit(this.id);" id="ans2">George Washington</button>
<button onclick="submit(this.id);" id="ans3">Thomas Edison</button>
<h4 id="answer"></h4>
j08691
  • 204,283
  • 31
  • 260
  • 272
subtrude
  • 35
  • 3
  • `var` variables are function scoped. `answer` created in `submit` does not exist in `answercheck` – Taplar Mar 11 '21 at 22:43

1 Answers1

0

The scope of your answer is wrong. It's bound to your submit function. Declare it outside of it so both functions can access it:

var answer;
function submit(clicked_id) {
  answer = document.getElementById(clicked_id).innerHTML;
  answercheck()
}

function answercheck() {
  if (answer != "George Washington") {
    document.getElementById("answer").innerHTML = "You are incorrect.";
  } else {
    document.getElementById("answer").innerHTML = "You are correct!";
  }
}
<h1>Quiz</h1>
<h3>Who is the first president of the United States?</h3>
<button onclick="submit(this.id);" id="ans1">Benjamin Franklin</button>
<button onclick="submit(this.id);" id="ans2">George Washington</button>
<button onclick="submit(this.id);" id="ans3">Thomas Edison</button>
<h4 id="answer"></h4>
j08691
  • 204,283
  • 31
  • 260
  • 272