Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .val() for select element returns text

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 comparison.

I know how to solve this with parseInt() or just comparing 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 comparison_value = 0;

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

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

    if ($('select').val() === comparison_value) {
        $('div#comparison').text('You just passed a test');
    } else {
        $('div#comparison').text('You just failed a test');
    }
})
<script src="https://ajax.googleapis.com/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='comparison'></div>
like image 472
codegaze Avatar asked Oct 26 '25 02:10

codegaze


1 Answers

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

like image 56
Denys Séguret Avatar answered Oct 27 '25 16:10

Denys Séguret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!