Assigning the correct answer to many inputs

I build a program that consists of a dozen sentences, each of them has input, which must be filled with the correct answer (eg. Jane is … (pretty) girl in our class), then you have to fill with the correct answer. The problem is that I have such sentences a dozen or so on different subpages. How can I assign the answers to each input without repeating the whole code? my code: https://jsfiddle.net/zxzc0/cpxseaL8/7/.

Hi @kd224mc, if you don’t mind having the correct answers in the markup, you might store them directly on the input fields as data-attributes:

<input type="text" class="input1" id="a1" data-answer="the prettiest">
<input type="text" class="input1" id="a2" data-answer="taller">
...
var inputs = document.querySelectorAll('.input1')

document.getElementById('checkAnswer').addEventListener('click', function () {
  inputs.forEach(function (input) {
    // Toggle the error class depending on whether the input value
    // differs from the answer specified in the data-atribute
    input.classList.toggle(
      'input1-wrongAnswer', 
      input.value !== input.dataset.answer
    )
  })
})
2 Likes

Thanks for your help, but how can I display answers like in my code with these attributes? The problem is that I do not know jquery yet, but it seems to me that just need to add a line that adds to the “answer” class the corresponding attribute from html, but I do not know how.

sorry that I wrote back so late but I did not have time.

Well there is no jQuery involved here. ;-) But yes, you can do exactly as you assumed; with the following HTML

<li>
  Jane is 
  <input type="text" class="input1" id="a1" data-answer="the prettiest"> 
  (pretty) girl in our class.
  <span class="answer"></span>
</li>
...

you can get the related answer span like so:

document.getElementById('showAnswer').addEventListener('click', function () {
  inputs.forEach(function (input) {
    // Get the related answer element (via the parent 
    // node as we can't query its siblings directly)
    var answerElement = input.parentNode.querySelector('.answer')
    // Set the text content to the answer stored on the input
    answerElement.textContent = '[ ' + input.dataset.answer + ' ]'
  })
})

PS: I would not recommend learning jQuery anyway unless you have to – the library is pretty much obsolete these days. It’s still more convenient than querying the DOM using the native API, but hardly worth the overhead.

2 Likes

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