How can val() return Number?

后端 未结 5 469
梦谈多话
梦谈多话 2020-11-27 19:28

In the valdocs written this description:

.val() Returns: String, Number, Array

I tried to get a Number, b

相关标签:
5条回答
  • 2020-11-27 19:47

    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);
    
    0 讨论(0)
  • 2020-11-27 19:58

    You could simply create a jquery plugin to use instead of val() that would do this. Here I create the function nval() to use instead of val() when fetching a elements value.

    $.fn.nval = function() {
       return Number(this.val())
    };
    

    Then in your code just use the following to get the value as a number

    $('#elementID').nval()
    
    0 讨论(0)
  • 2020-11-27 19:59

    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.

    0 讨论(0)
  • 2020-11-27 20:02

    Some HTML5 elements e.g. progress;

    console.log(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>

    0 讨论(0)
  • 2020-11-27 20:06

    Hmm. For all these in the console, jQuery $($0).val() and Javascript's $0.value return the string "3":

    <input type='number' value='3'/>
    <input type='text' value='3'/>
    <input type='radio' value='3'/>
    <input type='checkbox' value='3'/>
    

    So I think the jQuery val() documentation could be clearer. I can't see how it would ever return a number value so I'd suggest using parseInt($($0).val()) or parseFloat($($0).val()).

    0 讨论(0)
提交回复
热议问题