views:

22

answers:

2

i've tried several different variations of finding the length of a select element and nothing's working! i can't figure out why, since several websites list this is as the correct code.

here's the javascript:

<script type="text/javascript"> 
    alert(document.getElementById("opentimes").options.length);
</script>

and here's the form:

<form action="eateries.php" method="POST" name="filters">
        <select name="opentimes" id="opentimes" onChange="document.forms.filters.submit();">
            <option value="now">Open Now</option>
            <option value="tonight">Open Tonight</option>
            <option value="late">Open Late</option>
            <option value="whenever">Open Whenever</option>
        </select>
.......
</form>

i know the alert is working because i've tested it with simple strings. i've tried variations like document.filters.opentimes.length and document.forms.filters.opentimes.length but nothing works!

thanks.

+1  A: 

You're code is actually working, but I guess your code is executed before the DOM is loaded. Try this, for example:

<script type="text/javascript"> 
    window.onload = function(){
        alert(document.getElementById("opentimes").options.length);
    };
</script>

All code which is wrapped in window.onload = function(){ ... }; will be executed when the HTML-structure on the webpage is loaded. From that moment, you can use the document.getElementById() method.

Also, you can move your code down to the end of the document, but I wouldn't recommend that. It's ugly.

Harmen
ahh yes, that was the issue! i actually had the alert in a function but pasted it that way for simplicity. i was calling the function before the select was built. changed the order and it works now. thanks!
vee
+1  A: 

Order of execution. You're probably trying to access #opentimes before it exists in the DOM.

Try either putting your javascript below the <select> (in source order) or wrapping it in the body's load event.

2nd suggestion in action

<script type="text/javascript"> 
  onload = function()
  {
    alert(document.getElementById("opentimes").options.length);
  }
</script>

But be warned - you can often overwrite other "on load" functionality if other scripts are using it.

Peter Bailey
thanks for the solution!
vee