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 ?
<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>
<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>