Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery Doing Simple Math?

Tags:

jquery

I have a little DIV like this:

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

I'd like to use jQUery to either subtract or add by let say 1, resulting in 3 or 1...

is there a way in jquery to do this? convert a string to a int maybe?

like image 635
AnApprentice Avatar asked Nov 15 '10 18:11

AnApprentice


2 Answers

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

That way, the content from #counter are converted into an integer. This works great for numbers, but if for some reason something like "foo123" is the content, it would become NaN.

So another way to parse it is to use .parseInt()

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

parseInt() expects two arguments, a value and a radix (base number). If this is invoked on "foo123" it will return "123". One could say that this is a wrong behavior, so you need to decide which variant you want to have.

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

Ref.: .text()

like image 86
jAndy Avatar answered Nov 13 '22 18:11

jAndy


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

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

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

To add a check for negative, you could do this:

$('#counter').text(function(i,txt) {
    var result = parseInt(txt, 10) - 1;
    return (result > 0) ? result : 0; 
});
like image 4
user113716 Avatar answered Nov 13 '22 18:11

user113716