How to get background color changed if the user's answer is right?

I have an array of questions and answers. I just want that if the user types the right answer in the text field, the background color of the text field gets changed without any click. I have difficulty writing the code of checkAnswer function. Could you please help me write the correct code ?

<body>
    <div id="container">
        <h1> Press 'Enter' after writing your answer. </h1>
        <form>
            <input type="text" class="input" name="questions[]" />
            <input type="text" class="output" />
            <input type="text" class="input" name="questions[]" />
            <input type="text" class="output" />
            <input type="text" class="input" name="questions[]" />
            <input type="text" class="output" />
            <input type="text" class="input" name="questions[]" />
            <input type="text" class="output" />
            <input type="text" class="input" name="questions[]" />
            <input type="text" class="output" />
        </form>
        <a id="sub" href="#"> Submit </a>
        <div id="result"> </div>
    </div>
</body>



<script>
    var questions = [

        {
            question: "I like tea.",
            answer: "I do not like tea.",
            ans: "I don't like tea."
        },

        {
            question: "You are my friend.",
            answer: "You are not my friend.",
            ans: "You aren't my friend."
        },

        {
            question: "She is very naughty.",
            answer: "She is not very naughty",
            ans: "She isn't very naughty."
        },

        {
            question: "You can do it.",
            answer: "You cannot do it",
            ans: "You can't do it."
        },

        {
            question: "They are good.",
            answer: "They are not good.",
            ans: "They aren't good."
        },

    ];


    $('document').ready(function() {

        $.each(questions, function(i, x) {

            $('.input').eq(i).val(x.question);

            $('.input').prop('readonly', true);

        });

    });


  function checkAnswer() {

        for (i = 0; i < questions.length; i++) {

            let realanswer = questions[i];

            let useranswer = $('.output').val();

            if (realanswer.answer == useranswer) {

                $(".output").style.background = "green";

            }

        }

        checkAnswer();

    }

</script>

From this page, we learn about this method from this script:

<script>
function myFunction() {
  var x = document.getElementsByClassName("input");
  x[0].style.backgroundColor = "red";
}
</script>
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.