0

Hi Guys simple question (but failed to do this :( ). Just want to add all the numbers in <li>

PLeae check fiddle here http://jsfiddle.net/6j0xq49v/1/

Or you can check my code below

<ul>
    <li>2</li>
    <li>2</li>
    <li>2</li>
    <li>2</li>
    <li>2</li>
    <li>2</li>
</ul>
<button>Click</button>
<div class="total"><div>

SCRIPT

$('button').click(function(){
var thistext = 0;
$('ul li').each(function(){
    thistext = $(this).text();
    thistext += parseInt(thistext)
    alert(thistext)
})
})

Please help me guys Thanks in advance :)

2 Answers 2

2

You're assigning both the sum and each individual value to thistext. Try this:

$('button').click(function(){
  var thistext = 0;
  $('ul li').each(function(){
    thistext += parseInt($(this).text());
    alert(thistext);
  });
  $('.total').text(thistext);
});

Here's a working fiddle: http://jsfiddle.net/6m81xcp0/

UPDATE

If you need to account for the case where not all li elements contain numbers:

$('button').click(function(){
  var thistext = 0;
  $('ul li').each(function(){
    var text = $(this).text();
    if (isNaN(text)) { return; }
    thistext += parseInt(text);
    alert(thistext);
  });
  $('.total').text(thistext);
});

http://jsfiddle.net/6m81xcp0/1/

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for help .. but one more question .. if there is no number some <li> there is string then how to handle it for ur reff please check fiddle here jsfiddle.net/6j0xq49v/2
You can check whether the text value is a number by calling isNaN. See updated answer.
0

Remove this line:

thistext = $(this).text();

and use this way:

$('button').click(function() {
  var thistext = 0;
  $('ul li').each(function(a, v) {
     thistext += (+v.textContent); // parsing to number if prepend with +
  });
  $('.total').text(thistext);
  console.log(thistext);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>2</li>
  <li>2</li>
  <li>2</li>
  <li>2</li>
  <li>2</li>
  <li>2</li>
</ul>
<button>Click</button>
<div class="total">
  <div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.