Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get value as number?

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>
like image 490
santa Avatar asked Apr 18 '11 19:04

santa


2 Answers

Convert a string to a number in js like so:

var num = parseInt(lastVal, 10);
like image 85
Emmett Avatar answered Oct 05 '22 08:10

Emmett


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.

like image 36
Blender Avatar answered Oct 05 '22 07:10

Blender