开发者

finding the length of a form select element using javascript

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="o开发者_如何学Gopentimes" 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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜