I'm using the following to add one to number:
<div id="count">00</div>
<div id="count">03</div>
<div id="count">08</div>
<div id="count">12</div>
$('#count').text(function(i,txt) { return parseInt(txt, 10) + 1; });
I always want there two be 2 places, 00 even if the number is under 10. How can I get the func above, with JS, to always return the 2 00 places? So if the number computes to 3, it injects 03 into #count?
Thanks
In JavaScript “0” is equal to false because “0” is of type string but when it tested for equality the automatic type conversion of JavaScript comes into effect and converts the “0” to its numeric value which is 0 and as we know 0 represents false value. So, “0” equals to false.
In JavaScript, a number can be a primitive value (typeof = number) or an object (typeof = object). The valueOf() method is used internally in JavaScript to convert Number objects to primitive values. There is no reason to use it in your code. All JavaScript data types have a valueOf() and a toString() method.
$('#count').text(function(i,txt) { var c = parseInt(txt, 10) + 1; return (c<10) ? "0"+c : c; });
EDIT: But having multiple elements with the same ID is gonna cause problems somewhere.
Here's a little different approach from the others. Doesn't use a conditional operator.
$('#count').text(function(i, txt) {
return ("0" + (+txt + 1)).slice(-2);
});
It just assumes it will need the extra 0
, then returns a slice of the last two characters in the string.
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