Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can val() return Number?

In the valdocs written this description:

.val() Returns: String, Number, Array

I tried to get a Number, but it seems to return string only, Is there something that I'm doing wrong?

$('#gdoron').val('1');  alert($('#gdoron').val() === '1'); // true  alert(typeof $('#gdoron').val());  // string.  $('#gdoron').val(1);  alert($('#gdoron').val() === 1);  // false alert(typeof $('#gdoron').val()); // string (not "number"!)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="gdoron" />

My question is: how can val() return number as the docs says? The question is not about how can I parse the string.

like image 900
gdoron is supporting Monica Avatar asked Feb 10 '12 11:02

gdoron is supporting Monica


People also ask

Does val () return a string?

val()Returns: String or Number or Array. Description: Get the current value of the first element in the set of matched elements.

What does val() mean?

Definition and Usage The val() method returns or sets the value attribute of the selected elements. When used to return value: This method returns the value of the value attribute of the FIRST matched element. When used to set value: This method sets the value of the value attribute for ALL matched elements.

How to Get values in jQuery?

jQuery val() method is used to get the value of an element. This function is used to set or return the value. Return value gives the value attribute of the first element. In case of the set value, it sets the value of the attribute for all elements.

How to Get input element value in jQuery?

To get the textbox value, you can use the jQuery val() function. For example, $('input:textbox'). val() – Get textbox value.


1 Answers

A text input's value attribute will always return a string. You need to parseInt the value to get an integer:

parseInt($('#myInput').val(), 10); 
like image 71
osahyoun Avatar answered Sep 28 '22 19:09

osahyoun