Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to number and add one

I want to turn the value I get from the id into a number and add one to it then pass the new value into the dosomething() function to use. When I tried this and the value is one I get back 11 not 2.

$('.load_more').live("click",function() { // When user clicks     var newcurrentpageTemp = $(this).attr("id") + 1;// Get id from the hyperlink     alert(parseInt(newcurrentpageTemp));     dosomething(); }); 
like image 627
Niklas Avatar asked Oct 06 '11 12:10

Niklas


People also ask

How do you convert a string to a number in JavaScript?

How to convert a string to a number in JavaScript using the parseInt() function. Another way to convert a string into a number is to use the parseInt() function. This function takes in a string and an optional radix. A radix is a number between 2 and 36 which represents the base in a numeral system.

How do you convert one variable type to another say a string to a number?

Method 1: Using number_format() Function. The number_format() function is used to convert string into a number. It returns the formatted number on success otherwise it gives E_WARNING on failure. echo number_format( $num , 2);


2 Answers

Assuming you are correct and your id is a proper number (without any other text), you should parse the id and then add one to it:

var currentPage = parseInt($(this).attr('id'), 10); ++currentPage;  doSomething(currentPage); 
like image 121
Justin Niessner Avatar answered Oct 31 '22 10:10

Justin Niessner


Have you tried flip-flopping it a bit?

var newcurrentpageTemp = parseInt($(this).attr("id")); newcurrentpageTemp++; alert(newcurrentpageTemp)); 
like image 35
Doozer Blake Avatar answered Oct 31 '22 08:10

Doozer Blake