Reputation: 12512
I have a few elements with numeric IDs. Each ID is in a separate span. Can I get that value as a number in order to increment? I tries as text but it does not seem to work...
var lastVal = $(".myID:last").text();
var newVal = lastVal++;
Value <span class="myID">5</span>
Upvotes: 5
Views: 5083
Reputation: 14337
Convert a string to a number in js like so:
var num = parseInt(lastVal, 10);
Upvotes: 10
Reputation: 21378
Couple things here:
$('#btn').click(function(){
var lastVal = parseInt($("#txt").val(), 10);
var newVal = ++lastVal;
})
lastVal
to newVal
and then incrementing (which doesn't get added). Using pre increment, you modify the value of lastVal
before assignment (which is what you're looking to do).Upvotes: 1
Reputation: 112865
Use the parseInt
function to convert it from a string to a number:
var newVal = parseInt(lastVal, 10);
newVal++;
The second parameter to parseInt
, radix
, is optional and is used specify the base of your input string. Failure to supply this parameter causes the base to be determined automatically according to the following rules:
Upvotes: 1
Reputation: 91132
To convert a string to a number, you can use the parseInt
function. But to actually change it (if I understand your intent correctly), you want to do:
var elem = $('.myID');
var num = parseInt(elem.text());
elem.text(num+1)
// <span class="myID">5</span>
Upvotes: 1
Reputation: 298432
When you get the .text()
of an element, jQuery returns a string. You can't increment a string, so you'll have to make it an integer using the parseInt()
function:
var lastVal = parseInt($(".myID:last").text(), 10);
Now lastVal
contains an integer.
Upvotes: 2