简体   繁体   中英

How to write Text on HTML from Javascript Object

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:


  <body>
    <link rel="stylesheet" href="./style.css">
    <br>
    <br>
    <h6> What is 2 + 2 ? </h6>
    <br>
    <form action="PayslipServlet" method="get">
          My Answer:    <input type="text" name="ans" id="ans"><br/>
          <br>
          Evaluation of My Answer: <span id="eval"></span>
          <br>
          <!-- <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">
    </form>

    </script>
  </body>

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!

Well, you can access the question's text by using question_answer.question , and assign it as the h6's innerHTML .

Similarly for checking the answer, you can access it using question_answer.answer .

//will execute when the page loads
//so that we are sure the h6 did indeed load.
onload = function() {
  document.querySelector('h6').innerHTML = question_answer.question;
}

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

And as a side note, you do have some typos and markup errors, (an extra + symbol in the JS, and an extra </script> closing tag in your HTML).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM