Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
520 views
in Technique[技术] by (71.8m points)

javascript - Uncaught TypeError: Cannot set property 'onchange' of null

I am using a drop down for dynamically changing content on a page. It works but is throwing a js error in Chrome ONLY. What Chrome recommends I don't know how to implement. Site is built in ExpressionEngine 2.8.1.

ERROR MESSAGE IN CHROME

Uncaught TypeError: Cannot set property 'onchange' of null functions.js:65
event.returnValue is deprecated. Please use the standard event.preventDefault() instead.

MY JS Code

document.getElementById("drop").onchange = function() {
    if (this.selectedIndex!==0) {
        window.location.href = this.value;
    }        
};

MY HTML Code

            <form method="post" action="{path='locations/index'}" class="drop">
                <select id="drop">
                    <option>Select a Location:</option>
                {exp:channel:entries channel="locations" category="not 3" orderby="title" sort="asc" dynamic="no"}
                    <option value="{site_url}index.php/locations/{url_title}">{title}</option>
                {/exp:channel:entries}
                </select>
            </form>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There's only one possible reason for that error message, document.getElementById("drop") does not return the element, and the only reason for that is that the element doesn't exists, but in the HTML it clearly does, so the script must be running before the elements in the DOM.

You have to include the javascript after the elements in the DOM, or wrap it in a DOM ready handler, like window.onload etc.

<form method="post" action="{path='locations/index'}" class="drop">
    <select id="drop">
        <option>Select a Location:</option>{exp:channel:entries channel="locations" category="not 3" orderby="title" sort="asc" dynamic="no"}
        <option value="{site_url}index.php/locations/{url_title}">{title}</option>{/exp:channel:entries}
    </select>
</form>
<script>
    document.getElementById("drop").onchange = function() {
        if (this.selectedIndex !== 0) {
            window.location.href = this.value;
        }
    };
</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...