简体   繁体   中英

Javascript function not loading, no errors shown in chrome developer console

I am trying to create a simple javascript function which will populate 2 dropdown boxes, one for age and the other for gender.

However,the functions are not working and i cant seem to figure out why.Any help would be appreciated.

Code:

    <head>

<script type="text/javascript">

    function AgeDropDown(){
        var list=getElementById(UserProfileAge);
        for(var i=1;i<100;i++)
        {
            var opt = document.createElement("option");
            opt.value= i;
            UserProfileAge.appendChild(opt);
        }
    }

    function genderlist(){
        var choices=new array["M","F"];
        for(i=0;i<choices.length;i++)
        {
            var opt = document.createElement("option");
            opt.value= i;
            UserProfileGender.appendChild(opt);
        }
    }

</script>

</head>
<body>
<?php
include("usermenubar.inc");
?>
<form id='UserProfile' name='UserProfile' method='POST' action='editdetails.php'>


<div class='UserDetails'><!--dropdown-->
    Age:<select id='UserProfileAge' name='UserProfileAge' onclick='AgeDropDown'>
    <option value=''>Please enter your age</option>
    </select>
</div>

<div class='UserDetails'><!--Dropdown-->
    Gender:<select id='UserProfileGender' name='UserProfileGender' onclick="genderlist">
    <option value=''>Please enter your gender</option>
    </select>
</div>


<input type='submit' name='UserProfleSubmit' value='Save Changes'/>
</form>
</body>
</html>

This can help:

function load(){
    AgeDropDown();
    genderlist();
    }

 function AgeDropDown(){
        var list=document.getElementById("UserProfileAge");
        for(var i=1;i<100;i++)
        {
            var opt = document.createElement("option");
            opt.value= i;
            list.appendChild(opt);
        }
  }

    function genderlist(){
        var choices=new array["M","F"];
        for(i=0;i<choices.length;i++)
        {
            createOption(document.getElementById("UserProfileGender"));
        }
    }

Your functions are loading, but they are never executed because they are never called. You have to call the function at some point in your html file. The best practices it to run initialization code like on onload event of the page.

<script>
function load()
{
  AgeDropDown();
  genderlist()
}
... 
</script>



<body onload="load()">

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