Home » Jquery » How can val() return Number?

How can val() return Number?

Posted by: admin November 29, 2017 Leave a comment


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?


alert($('#gdoron').val() === '1'); // true 
alert(typeof $('#gdoron').val());  // string.


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" />

Some HTML5 elements e.g. progress;

alert(typeof $("#prog").val()); // number 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<progress value="50" max="100" id="prog"></progress>


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);


I’ve done a bit of quick peeking around, and I think I have an answer. If you look at the implementation of the val function you can see that if a so-called val-hook is in place, if the val-hook returns a number, that number will be returned as-is from the val function. I found this discussion which suggests that val-hooks are primarily used by plugins to create custom controls, such as sliders, etc., where the “natural” return value of val could be an integer. Hope this sheds a bit of light on your question.