Create a tally system with JavaScript

I would like to create a simple tally system to record the data-id from the elements that are selected and combine the data-id values at the end to generate a result.

function myAnswer() {
  document.getElementById('btnNxt').removeAttribute('disabled');
  var myResult = '';
  var iId = this.getAttribute('data-id');
  myObj[page].mySel = iId;
  myQueRep[page] = iId;
  console.log(iId);
  for (var x = 0; x < btn.length; x++) {
    if (iId == x) {
      btn[x].classList.add('selAnswer');
    } else {
      btn[x].classList.remove('selAnswer');
    }
 }

}

In this section, the iId variable gets the data-id value but I'm not sure how to tally the selections up and display a result based on that score.

JSFiddle of current code:

https://jsfiddle.net/mkykmg15/2/

1 answer

  • answered 2018-04-14 15:49 A. Lau

    You should be doing something with your myQueRep.

    So something like:

    var myQueRep = ["1", "1", "1", "2", "2", "2"]
    
    var tally = myQueRep.reduce( function (acc, curr) {
      return acc + +curr
    }, 0);
    
    console.log(tally)