D
D
Demon2015-10-23 09:13:20
JavaScript
Demon, 2015-10-23 09:13:20

How to add numbers from div?

Example:

<div id="load_numAll-shet" style="display:none">
<div data="10" id="load_numAll" >10</div>
<div data="50" id="load_numAll" >50</div>
<div data="70" id="load_numAll" >70</div>
<div data="80" id="load_numAll" >80</div>
</div>
<div id="load_numAll-show"></div>

How can I add up all the data numbers and display the added sum in a div!.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Alexander, 2015-10-23
@freelancer

var items = document.getElementById('load_numAll-shet').innerText;
var sum = items.split('\n').reduce(function(a,b){return a*1+b*1});
document.getElementById('load_numAll-show').innerHTML = sum;

V
Vitaly Inchin ☢, 2015-10-23
@In4in

1. There is no data attribute as such, use data-* attributes .
2. It is impossible to set the same id to several elements, there are classes.
3. What is the extra attribute for, if the same value is inside the blocks?
4. Read some books about valid layout.

<ul id="load_numAll-shet" style="display:none">
   <li data-n="10" class="load_numAll-li">10</li>
   <li data-n="50" class="load_numAll-li">50</li>
   <li data-n="70" class="load_numAll-li">70</li>
   <li data-n="80" class="load_numAll-li">80</li>
</ul>
<output id="load_numAll-show"></output>

var output = document.querySelector("#load_numAll-show"),
   lies = document.querySelectorAll(".load_numAll-li");

output.value = Array.prototype.reduce.call(
   lies, function(p, t){
      return p + (+t.dataset.n);
    }, 0
);

N
Nikolai Shabalin, 2015-10-23
@nikolayshabalin

In general, your mistakes have already been pointed out to you and I will not repeat them. Here's my version of your code.
HTML

<div id="load_numAll-shet" style="display:none">
    <div data-num="10" id="load_numAll" >10</div>
    <div data-num="50" id="load_numAll" >50</div>
    <div data-num="70" id="load_numAll" >70</div>
    <div data-num="80" id="load_numAll" >80</div>
</div>
<div id="load_numAll-show"></div>

jQuery
var $showBox = $('#load_numAll-show');
var $numbers = $('#load_numAll-shet div');
var sum = 0;

$numbers.each(function() {
    sum += parseInt($(this).data('num'));
});

$showBox.text(sum);

Slightly different in JS
var $showBox = document.getElementById('load_numAll-show');
var $numbers = document.querySelectorAll('#load_numAll-shet div');
var sum = 0;

for(var i = 0; i < $numbers.length; i++) {
    sum += Number($numbers[i].dataset.num);
}

$showBox.innerText = sum;

You can play here

N
newimageru, 2017-12-20
@newimageru

How to add numbers dynamically? Do not tell me? Is there a block in inputami? the selected ones are passed to #load_numAll-shet.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question