Home > Enterprise >  Count multiple div class in same page
Count multiple div class in same page

Time:05-21

I am trying to make a correct and incorrect question counter that shows groups of 4.

If I click on the first correct answer the counter works correctly and increases as I click, but it does not work with the second correct answer. The same happens with the wrong answers

This is the codes that I use, anyone could help me? Thx

SITE EXAMPLE: https://foropositores.com/temas/prueba.53921/

HTML CODE:

    ¿Which of the following operations results in 8?
<input  value="6 2">
<input  value="7 1">
<input  value="1 1">
<input  value="2 2">

And the JS CODE:

<!-- CONTADOR FALLOS TEST -->
<script type="text/javascript">
var root = document.querySelector('.solucionincorrecta');

root.onclick = function() { 
var elem = document.getElementById('contadorfallos');
  elem.innerHTML =  elem.innerText   1;
};
</script>
<!-- CONTADOR FALLOS TEST -->


<!-- CONTADOR ACIERTOS TEST -->
<script type="text/javascript">
var root = document.querySelector('.solucioncorrecta');

root.onclick = function() { 
var elem = document.getElementById('contadoraciertos');
  elem.innerHTML =  elem.innerText   1;
};
</script>

CodePudding user response:

The issue is that you are using document.querySelector() and not document.querySelectorAll()

document.querySelector() Returns the first match

document.querySelectorAll() Returns all matches

As a result, you are only setting an onclick property on the first .correcta and .incorrecta elements, not all of them.

To set this on all of them, you need to do two things:

  1. You need use document.querySelectorAll() instead of document.querySelector(). This returns a list (specifically, a NodeList) of matching elements.
  2. Loop over the items in your list, and attach onclick handlers to each of them. There are many ways to loop over a NodeList, listed here.

Here is an example:

// get all incorrect elements
var incorrectElements = document.querySelectorAll('.incorrecta');

// loop over each elements
for (var element of incorrectElements) {
  // add an onclick
  element.onclick = incorrectClickHandler
}

// this is the function being called by onclick
function incorrectClickHandler() {
  score.innerText = parseInt(score.innerText) - 1;
}

CodePudding user response:

It would be better if you upload your full codes. But anyway I write you some notes that probably answer your question.

-dont use the same name (root) for your .correcta and .incorrecta

-in your second <script>, you didnt defined button as an object . So browser cant understand it.

  • Related