简体   繁体   中英

Alternative to window.onload event for dynamically building drop downs

I have created a dynamic drop down list. Currently I am building the drop downs on "window.onload" event. But the problem is, I can no longer use windows.onload because this event is now being already used by "myFile.jsp" file which I have included in the body. Since 2 onload events don't work simultaneously, so I am looking for some other way out to build the drop downs. Can you please help. I am very new to web development.

My HTML file

<!DOCTYPE html>

</head>
<body>
    <jsp:include page="/myFile.jsp"></jsp:include>
    <table align="center" cellspacing="3" cellpadding="3">
        <tr>
            <td>County Name: </td>
            <td><select id="county"><option value="">Select county</option></select></td>
        </tr>
        <tr>
            <td>City: </td>
            <td><select id="city"><option value="">Select city</option></select></td>
        </tr>
    </table>
    <button  class="btn" onclick="doThis()"">Go</button>
</body>

My js file:

    function doc(id){return document.getElementById(id);}
        function buildCounty(){
            var opts=doc('county').options;
            for(var i=0;i<arr.length;i++){
                opts[opts.length]=new Option(arr[i][0],arr[i][0]);
            }
            doc('county').onchange=function(){
                this.blur();
                var val=this.value;
                if(!val){return;}
                var co=doc('city').options;
                co.length=1;
                for(var j=0;j<arr.length;j++){
                    if(arr[j][0]!==val){continue;}
                    else{
                        var temp=arr[j][1];
                        for(var k=0;k<temp.length;k++){
                            co[co.length]=new Option(temp[k],temp[k]);
                        }
                        break;
                    }
                }
            }
        }
        function doThis(){

        }
        window.onload=buildCounty;
    </script>

Try the following jQuery...

$(function() {
  buildCounty();
});

$(function() {...}); is the equivalent of window.onload and will not overwrite any existing calls (eg you can have as many of them in your code as you like)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM