Nate
Nate

Reputation: 28384

Can't get value of select box in IE or Chrome?

I've been building my site in FF and just realized that it's not working in IE or Chrome (the Javascript, that is). Using IE's JS debugger I found that it is spitting out the following error:

SCRIPT5007: Unable to get value of the property 'value': object is null or undefined ...

For the following code:

var myvar = document.getElementById("selectboxid").value;

It works fine in FF, but not in IE or Chrome.

The HTML for the select box looks like this:

<select name="selectboxid" id="selectboxid" size="1" autocomplete="off" tabindex="5" >
<option value="1">One</option>
<option value="2">Two</option>
...

Am I doing something wrong? If so, why does it work fine in FF?

Thanks for your help.

Upvotes: 2

Views: 4509

Answers (1)

Jeff Robert Dagala
Jeff Robert Dagala

Reputation: 633

you could use this:

var myvar = document.getElementById("selectboxid");
var selectedValue = myvar.options[myvar.selectedIndex].value; //This will get the selected value of the select box

example to implement this:

<html>
<head>
    <title>sample</title>
</head>
<body>
    <select name="selectboxid" id="selectboxid" onchange="alertValue()" size="1" autocomplete="off" tabindex="5">
        <option value="1">One</option>
        <option value="2">Two</option>
        <option value="3">Three</option>
        <option value="4">Four</option>
    </select>
    <script type="text/javascript">
    function alertValue() //this function will only be called when the value of select changed.
    {
        var myvar = document.getElementById("selectboxid");
        var selectedValue = myvar.options[myvar.selectedIndex].value; //This will get the selected value of the select box
        alert(selectedValue);
    }
    </script>
</body>
</html>​

Upvotes: 4

Related Questions