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?
$('#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()
$('#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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With