Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery get text as number

This code doesn't work:

var number = $(this).find('.number').text(); var current = 600; if (current > number){      // do something } 

HTML:

<div class="number">400</div> 

Seems there is some problem with converting text() from text-like value to number.

What is the solution?

like image 598
James Avatar asked Aug 23 '10 11:08

James


People also ask

What does VAL () do in jQuery?

val() method is primarily used to get the values of form elements such as input , select and textarea . When called on an empty collection, it returns undefined . When the first element in the collection is a select-multiple (i.e., a select element with the multiple attribute set), .

How do I get text inside a div using jQuery?

To get the value of div content in jQuery, use the text() method. The text( ) method gets the combined text contents of all matched elements. This method works for both on XML and XHTML documents.

How do I get inner text in jQuery?

Answer: Use the jQuery text() method You can simply use the jQuery text() method to get all the text content inside an element. The text() method also return the text content of child elements.

How can get textarea value in jQuery using ID?

We can get the value of textarea in jQuery with the help of val() method . The val() method is used to get the values from the elements such as textarea, input and select. This method simply returns or sets the value attribute of the selected elements and is mostly used with the form elements.


2 Answers

Always use parseInt with a radix (base) as the second parameter, or you will get unexpected results:

var number = parseInt($(this).find('.number').text(), 10); 

A popular variation however is to use + as a unitary operator. This will always convert with base 10 and never throw an error, just return zero NaN which can be tested with the function isNaN() if it's an invalid number:

var number = +($(this).find('.number').text()); 
like image 124
RoToRa Avatar answered Sep 18 '22 10:09

RoToRa


myInteger = parseInt(myString);

It's a standard javascript function.

like image 36
Trimack Avatar answered Sep 19 '22 10:09

Trimack