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?
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), .
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.
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.
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.
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());
myInteger = parseInt(myString);
It's a standard javascript function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With