Test with questions and answers in HTML code in JavaScript

In this and in the next few lessons, we will create tests with questions and answers. We start with the simplest options and gradually will complicate them.

Let's start by making a set of questions, each of them can have only one answer. Let the answers be entered by the user into the inputs under the questions themselves.

I'll illustrate it with HTML code:

<div id="test"> <div> <p>question 1?</p> <input> </div> <div> <p>question 2?</p> <input> </div> <div> <p>question 3?</p> <input> </div> </div>

As you can see, we have questions and inputs for answers. It remains to figure out where we will store the correct answers.

The simplest thing you can think of is to store the answers directly in the HTML code of the inputs, in some data- attribute:

<div id="test"> <div> <p>question 1?</p> <input data-right="answer 1"> </div> <div> <p>question 2?</p> <input data-right="answer 2"> </div> <div> <p>question 3?</p> <input data-right="answer 3"> </div> </div>

The next nuance to think about is: at what point will we check the answers for correctness? Two options could be suggested here: either let each input check whether this answer is correct immediately after entering the answer into it, or let there be a button, by clicking on which the answers to all questions will be checked at once.

Whichever option we choose, let's, if the answer is correct, then we will paint the input border in green, and if it is wrong - in red. Let's make appropriate CSS classes for this:

.right { border: 1px solid green; } .wrong { border: 1px solid red; }

Make it so that entering the answer into the input is completed by pressing the Enter key. Let in this case, the input immediately checks the answer for correctness.

Modify your code so that the answers are checked when the button is clicked.

enru