Moshe Shaham
Moshe Shaham

Reputation: 15974

jquery select box bug in internet explorer

I'm using jquery 1.2.6 (can't upgrade because it part of a system). I'm getting a weird error.

this is my code:

<!DOCTYPE html>
<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
    </head>
    <body>
        <select id="state" name="state">
            <option selected="selected"></option>
                        <option value="none">N/A</option>
                        <option value="AK">AK</option>
                        <option value="AL">AL</option>
                        <option value="AR">AR</option>
                        <option value="AZ">AZ</option>
                        <option value="CA">CA</option>
        </select>
    </body>
</html>
<script type="text/javascript">
    $(function() {
        var test = $('#state').val();
    });
</script>

when I test in IE9 I'm getting this error when loading the page:

"Unable to get value of the property 'specified': object is null or undefined" 

Why is that?

Upvotes: 4

Views: 921

Answers (2)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382102

The value in an option is optional ("If there isn't, the value of an option element is the textContent of the element."). So you seem to encounter a bug here.

I had a look at the old jQuery source code and I found the bug :

value = jQuery.browser.msie && !option.attributes.value.specified ? option.text : option.value;

option.attributes.value is undefined so option.attributes.value.specified crashes.

As the bug is in jQuery (more precisely in what looks like an attempt to work around an old IE bug now fixed), it would be legitimate to not use jQuery on this particular task.

Instead of changing the HTML (your HTML is fine), I recommend to use, as a workaround, the vanilla JS solution :

var test = document.getElementById('state').value;

Note that when I say that the bug is in jQuery, it mainly means the 2008 version of jQuery fails in recent versions of IE while trying to work around bugs of 2008 browsers. You should really tell your architect that keeping this old jQuery isn't a sound decision.

Upvotes: 4

Your selected option does not have a value set, so that is why it is complaining :)

Upvotes: 2

Related Questions