ima007
ima007

Reputation: 477

Why is jQuery.val returning an array instead of a string in Internet Explorer 7 (IE7)?

I'm trying to grab the value from the following select element. Say the user selects the first option.

<select class="your-class" type="text">
    <option value='one'>One</option>
    <option value='two'>Two</option>
    <option value='three'>Three</option>
</select>

The javascript:

$("select.your-class").val()
//returns ["one"] in IE7, returns "one" in other browsers

Why is IE7 returning an array, instead of a single string? This isn't a select multiple element.

Upvotes: 1

Views: 522

Answers (1)

ima007
ima007

Reputation: 477

The issue is the type attribute that seems to have been erroneously added to the select element (maybe it was originally a text input element and it was switched to a select)?. Remove the attribute to resolve the issue.

Under the covers, jQuery is using the following boolean to determine if your select element is a select one (the standard select box) or a select multiple (select element with the multiple attribute).

var IsSelectOne = elem.type === "select-one" || elem.selectedIndex < 0;

Setting the type attribute overrides the default value of 'select-one' in IE7, which causes this boolean to be false. Since the boolean is false, this tells jQuery that you have a select-multiple element, and it provides you with an array, instead of a single string.

Upvotes: 8

Related Questions