Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript OnChange Listener position in HTML markup

I am having problems getting the OnChnage Listener to work, if i position the script after the </form> tag the listener works fine but if i place the script within the <head> tags it fails to work.

On my site i can only have the script within the <head> tags is there anything I can do to make the script runn within the <head> tags?

in this configuration the script does not work

<head>
<script type="text/javascript">
if(window.addEventListener) {
    document.getElementById('address').addEventListener('change', loadXMLDoc, false);
} else if (window.attachEvent){
    document.getElementById('address').attachEvent("onchange", loadXMLDoc);
}

function loadXMLDoc(){
   alert('worked');
}
</script>
</head>

<body>
<form>

<input id="address" name="address" type="text"/>
<input id="test" name="test" type="text"/>

 </form>
like image 734
Cookiimonstar Avatar asked Aug 29 '12 19:08

Cookiimonstar


2 Answers

Put it this way:

<head>
<script type="text/javascript">
window.onload= function () {
    if(window.addEventListener) {
        document.getElementById('address').addEventListener('change', loadXMLDoc, false);
    } else if (window.attachEvent){
        document.getElementById('address').attachEvent("onchange", loadXMLDoc);
    }

    function loadXMLDoc(){
       alert('worked');
    }
}
</script>
</head>
like image 85
Teemu Avatar answered Oct 03 '22 08:10

Teemu


Put your code in the window.onload function:

<head>
<script>
    window.onload = function() {
        if(window.addEventListener) {
            document.getElementById('address').addEventListener('change', loadXMLDoc, false);
        } else if (window.attachEvent){
            document.getElementById('address').attachEvent("onchange", loadXMLDoc);
        }

        function loadXMLDoc(){
            alert('worked');
        }
    }
</script>
<body>
    ...
</body>
like image 22
Ethan Brown Avatar answered Oct 03 '22 08:10

Ethan Brown