Harper
Harper

Reputation: 1

jquery create counter with value from div

I am trying to create a script with jquery that pulls a number from a specified div (#counter below) and adds 100 to it every second and updates the number in the div. I've tried a number of things, but nothing with the intended result. Any tips? Here is what I have currently:

<script type="text/javascript">

setInterval("counter()", 1000); // run counter function every second

function counter() {
  var count = $("#counter").val();  // get value of counter div
  var total = count+100;  // add 100 to value of counter div
  $("#counter").text(total); // update counter div
}

</script>

<div id="counter">1000</div>

Upvotes: 0

Views: 2077

Answers (5)

Christian Stewart
Christian Stewart

Reputation: 15519

Here is the working code: http://jsfiddle.net/FbJPY/3/

The issue is that your interval is not working, as well as you're not parsing a number from the contents of the div.

Fixes:

  • Interval should reference a function, not a variable, so you can type counter without quotes.

  • You need to parse the number from the contents of the div.

setInterval(counter, 1000); // run counter function every second

function counter() {
  var count = parseInt($("#counter").text(), 10);  // get value of counter div
  var total = count + 100;  // add 100 to value of counter div
  $("#counter").text(total); // update counter div
}

Upvotes: 0

Nathan
Nathan

Reputation: 1700

Try casting count to an integer?

var total = parseInt(count, 10) + 1000;

Should use jquery html() as opposed to val() unless it is a form input.

var count = $('#counter').html();

Also noticed you are not passing the function reference correctly to setInterval()

setInterval(counter, 1000);

Upvotes: 0

Sol
Sol

Reputation: 1173

Edit - adding parseInt like others mentioned.

You're not calling counter() correctly and you should use .html() instead of val() like this:

<script type="text/javascript">

setInterval(counter, 1000); // run counter function every second

function counter() {
  var count = $("#counter").html();  // get value of counter div
  var total = parseInt(count)+100;  // add 100 to value of counter div
  $("#counter").text(total); // update counter div
}

</script>

<div id="counter">1000</div>

Upvotes: 1

Blender
Blender

Reputation: 298106

A few changes:

function counter() {
    var count = parseInt($('#counter').text(), 10);
    $('#counter').text(count + 100);
}

setInterval(counter, 1000);
  1. Don't pass a string to setInterval. Always pass a function.
  2. .val() is only for <input> elements. You need to use .text() (which will return a string), so you need to parse the text into an integer with parseInt(). The 10 tells parseInt to assume base-10.

Upvotes: 2

fedeghe
fedeghe

Reputation: 1318

use

parseint($("#counter").html(), 10) // or ~~$("#counter").html()

and even

$("#counter").html(total)

instead

Upvotes: 0

Related Questions