2I would like to use jquery to subtract or add, let it say 1, ...">

JQuery Simple math?

I have a little DIV like this:

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

I would like to use jquery to subtract or add, let it say 1, the result is 3 or 1 ...

Is there a jquery way to do this? convert string to int, maybe?

+5
source share
6 answers
$('#counter').text(function(i,txt) { return parseInt(txt, 10) + 1; });

Example for adding: http://jsfiddle.net/2uBMy/

Example for subtraction: http://jsfiddle.net/2uBMy/1/

To add a check to a negative, you can do this:

$('#counter').text(function(i,txt) {
    var result = parseInt(txt, 10) - 1;
    return (result > 0) ? result : 0; 
});
+4
source
$('#counter').text(function(i, txt) {
    return +txt + 1;
});

Thus, the contents of the #counterconverted to an integer. This works fine for numbers, but if for some reason something like "foo123" is content, it will become NaN.

, - .parseInt()

$('#counter').text(function(i, txt) {
    return parseInt(txt, 10) + 1;
});

parseInt() , ( ). "foo123", "123". , , , .

: http://www.jsfiddle.net/Mtvju/

Ref.: . text()

+8
$('#counter').html(  +($('#counter').html()) + 1 );
+1
var counter = $('#counter');
var value   = parseInt(counter.html());
counter.html(value + 1);
+1

, int. parseInt, . jQuery . Html, <div> .

$("#counter").html(parseInt($("#counter").html(),10) + 1)
$("#counter").html(parseInt($("#counter").html(),10) - 1)

!

0

javascript . , , . , , +, . - .

function subtract()
{
   count = $('#counter').html();
   if(count > 0)
   {
     count--;
   }
   $('#counter').html(count)
}
0
source

All Articles