最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery .val() for select element returns text - Stack Overflow

programmeradmin4浏览0评论

Does jQuery .val() for select elements returns only text and not numbers? You know there is a problem when you need to make a value parison.

I know how to solve this with parseInt() or just paring with string or by not using jQuery at all but what I don't know if this is a bug or the way jQuery just works.

From jQuery documentation > Value: Type: String or Number or Array A string of text, a number, or an array of strings corresponding to the value of each matched element to set as selected/checked.

.val() Returns: String or Number or Array

// Put any number here 0 is the default selected value
var parison_value = 0;

$('button').click(function () {

    $('div#typeof').text(typeof ($('select').val()));

    if ($('select').val() === parison_value) {
        $('div#parison').text('You just passed a test');
    } else {
        $('div#parison').text('You just failed a test');
    }
})
<script src=".11.1/jquery.min.js"></script>
<select>
    <option value="0" selected>Select Something</option>
    <option value="1">One</option>
    <option value="2">Two</option>
</select>
<button>Gimme back my selection</button>
<div id='typeof'></div>
<div id='parison'></div>

Does jQuery .val() for select elements returns only text and not numbers? You know there is a problem when you need to make a value parison.

I know how to solve this with parseInt() or just paring with string or by not using jQuery at all but what I don't know if this is a bug or the way jQuery just works.

From jQuery documentation > Value: Type: String or Number or Array A string of text, a number, or an array of strings corresponding to the value of each matched element to set as selected/checked.

.val() Returns: String or Number or Array

// Put any number here 0 is the default selected value
var parison_value = 0;

$('button').click(function () {

    $('div#typeof').text(typeof ($('select').val()));

    if ($('select').val() === parison_value) {
        $('div#parison').text('You just passed a test');
    } else {
        $('div#parison').text('You just failed a test');
    }
})
<script src="https://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select>
    <option value="0" selected>Select Something</option>
    <option value="1">One</option>
    <option value="2">Two</option>
</select>
<button>Gimme back my selection</button>
<div id='typeof'></div>
<div id='parison'></div>

Share Improve this question edited May 23, 2015 at 13:43 A. Wolff 74.4k9 gold badges97 silver badges157 bronze badges asked May 23, 2015 at 12:35 codegazecodegaze 7557 silver badges15 bronze badges 5
  • 2 An elements value is always a string, it's never of the type Number. It has nothing to do with jQuery, it's the way it's defined in the specification. – adeneo Commented May 23, 2015 at 12:38
  • 2 You posted quotes regarding setter val() method – A. Wolff Commented May 23, 2015 at 12:39
  • 1 ^^ val(value) - setter. – Shaunak D Commented May 23, 2015 at 12:41
  • @A.Wolff: that's what I wanted to say as well, but the docs for the getter also say it would return a string, number or array. So it doesn't really matter. – Felix Kling Commented May 23, 2015 at 12:45
  • @FelixKling True (and i missed that) even i'm not sure in which case it returns a number. Then i read Karl-Johan's answer, could explain it. – A. Wolff Commented May 23, 2015 at 13:41
Add a ment  | 

2 Answers 2

Reset to default 5

You get what you've set in the value attribute of the select element, the value, which is "1" or "2", but as a string, input values are never anything else than strings (even if you may have accessors like valueAsNumber in HTML5).

If you want to get it as a number, use

var selectedValue = +$('select').val();

If you want the index of the selected option, use

var selectedIndex = $('select')[0].selectedIndex;

Now, regarding the excerpt of the documentation you cite: it's about setting the value. If you pass a number, it will be converted to a string (and you'll get a string if you call .val() to get the value).

What you are reading is the description of the value argument, not the returned value.

If we look at the source for .val() in the awesome jQuery Source Viewer we can see that there is a snippet to convert numbers to strings and joining arrays before setting them as a value.

// Treat null/undefined as ""; convert numbers to string
if (val == null) {
    val = "";
} else if (typeof val === "number") {
    val += "";
} else if (jQuery.isArray(val)) {
    val = jQuery.map(val, function (value) {
        return value == null ? "" : value + "";
    });
}

You did however seem to want return values and .val() is in theory able to return numbers if we trust the jQuery documentation which states Returns: String or Number or Array. The result is checked if the type is a string, if so \r is stripped out and the string returned, else there is a null-check which might return the actual value or an empty string (which is mented to work for numbers or null-values).

return typeof ret === "string" ?
    // handle most mon string cases
    ret.replace(rreturn, "") :
    // handle cases where value is null/undef or number
        ret == null ? "" : ret;

The rreturn variable is declared in the global namespace as var rreturn = /\r/g; so you can't find it with the source browser.

So the real question here is can the DOM actually return numbers as values? The answer here seems to be "Yes, but only if you explicitly ask for it".

Since HTML5 there is a new valueAsNumber-property on the HTMLInputElement interface that will return the value as a number is possible or NaN if not. This seems to only apply to HTMLInputElement though and is for example not available in the HTMLSelectElement interface.

I did a quick search through the latest jQuery sources (both latest nightly and the 1.11 release) and none of them use valueAsNumber today. Just speculating here, but this might have been added to the documentation before valueAsNumber was proposed just in case.

So it seems that you are stuck with strings for the moment unless you yourself use valueAsNumber (and it should really just be used on <input type="number" /> or <input type="range" /> unless you add some manual validation).

发布评论

评论列表(0)

  1. 暂无评论