2

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.

Nate
  • 26,164
  • 34
  • 130
  • 214

1 Answers1

4

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>​
  • I just tried this and am getting the error "SCRIPT5007: Unable to get value of the property 'options': object is null or undefined ..." – Nate Oct 25 '12 at 00:29
  • what browser are you using? when did you call the javascript? before or after the select element? – Jeff Robert Dagala Oct 25 '12 at 00:31
  • It appears that the element in question is not present when the code is run. Jeff's suggestion works as expected in jsFiddle (in Chrome). – Kevin Boucher Oct 25 '12 at 00:31
  • @JeffRobertDagala - I'm trying it in IE9 and Chrome. The javascript is in the html file at the bottom of the page. – Nate Oct 25 '12 at 00:36
  • @KevinBoucher - the code is run when a checkbox is checked, so the page has been loaded for a long time when the code runs. – Nate Oct 25 '12 at 00:37
  • can you post your script when the checkbox was checked? – Jeff Robert Dagala Oct 25 '12 at 00:49
  • updated my answer with a sample on how to implement it. it works on IE9 and Chrome Version 22 – Jeff Robert Dagala Oct 25 '12 at 01:01
  • Jeff, thanks so much for your help. I found a stupid little typo in my code that was breaking it. After correcting that, your code worked. Thanks! – Nate Oct 25 '12 at 01:13