santa
santa

Reputation: 12512

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>

Upvotes: 5

Views: 5083

Answers (5)

Emmett
Emmett

Reputation: 14337

Convert a string to a number in js like so:

var num = parseInt(lastVal, 10);

Upvotes: 10

Demian Brecht
Demian Brecht

Reputation: 21378

Couple things here:

$('#btn').click(function(){
   var lastVal = parseInt($("#txt").val(), 10); 
   var newVal  = ++lastVal;
})
  1. You can use parseInt to get the numeric value from the text
  2. Try pre-incrementing opposed to post here. Using post increment, you're assigning the value of 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).

Sample here

Upvotes: 1

Donut
Donut

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:

  • If the string begins with "0x", the base is assumed to be 16.
  • If the string begins with "0", the base is assumed to be 8.
  • If the string begins with anything else, the base is assumed to be 10.

Upvotes: 1

ninjagecko
ninjagecko

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

Blender
Blender

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

Related Questions