Garmaine Staff asked 1 year ago

My goal is to write web app that presents a question and gets an answer from the user and compare that with known answer and tell him/her if he/she got answer correct/incorrect.

Right now "the question" is hard-coded HTML (please see below in my code). The answer is also hard-code in the JS code. Only the comparison happens in the JS function.

In the JS code , I have defined the question and answer as an object.

Now, I would like the question (presented on the HTML web page) and answer to dynamically come from the JS object.

It feels like I am going about this the wrong. Maybe there is better way altogether?

My HTML Code:

    <link rel="stylesheet" href="./style.css">
    <h6> What is 2 + 2 ? </h6>
    <form action="PayslipServlet" method="get">
          My Answer:    <input type="text" name="ans" id="ans"><br/>
          Evaluation of My Answer: <span id="eval"></span>
          <!-- <input type="button" class="button" value="Submit" onClick="check_answer()"> -->
          <script type="text/javascript" src="check_answer_v2.js"></script>
          <input type="button" class="button" onclick="check_answer()" value="Submit">


My javascript code (check_answer_v2.js)

var question_answer = {
  question: "What is 2 + 2 ?",
  answer: "4", 

function check_answer() {
            given_ans = +document.getElementById('ans').value
            // document.getElementById("eval").innerHTML = typeof given_ans  ; 
            if (given_ans == 4) {
              document.getElementById("eval").innerHTML = 'Correct'  ; 
            } else {
              document.getElementById("eval").innerHTML = 'Incorrect'  ; 

Any help is appreciated!