1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

How to total numbers within a div

Discussion in 'JavaScript' started by Vinniexxx_4, Feb 25, 2019.

  1. #1

    This is the first time i am on this forum and hope someone can help.

    I have created a 2 player Dice game. The idea is that each player in turn rolls the dice. This is a 6 sided each, 2 dice per player.
    After each roll the numbers need to be added.

    I am trying to extract numbers and then total these numbers using javascript.
    so far i have a <div id="score">5,2,10,13</div>

    The numbers within the div i need it to total e.g 30

    Many Thanks
    Vinniexxx_4, Feb 25, 2019 IP
  2. RoseHosting

    RoseHosting Well-Known Member

    Likes Received:
    Best Answers:
    Trophy Points:
    Something like this should work:

    var numbers = document.getElementById('score').innerHTML.split(",");
    var sum = 0;
    for (var i = 0; i < numbers.length; i++) {
      sum += parseInt(numbers[i]);
    Code (JavaScript):
    RoseHosting, Feb 25, 2019 IP
  3. Vinniexxx_4

    Vinniexxx_4 Peon

    Likes Received:
    Best Answers:
    Trophy Points:
    I am getting the following response 'NaN' to your code.

    This is my code:

    var myScore = document.getElementById("score");
    var die3 = document.getElementById("die3");
    var die4 = document.getElementById("die4");
    var d3 = Math.floor(Math.random()*5)+1;
    var d4 = Math.floor(Math.random()*5)+1;
    var Total = d3 + d4;
    die3.innerHTML = d3;
    die4.innerHTML = d4;
    var score=0;
    let sum = Total.reduce((Total, val)=>{
    return Total + val;},0);
    myScore.innerHTML +=""+sum+",";
    Code (markup):
    I get the following output <div id='score'> 12,10,9,1,2</div> I tried using innerText which strips the div tag and gives me 12,10,9,1,2 which works but I want a total of these numbers?
    Vinniexxx_4, Feb 25, 2019 IP