Javascript 下拉列表工作,但显示空值

标签 javascript jquery html

我有 2 个用 javascript 编写的下拉列表。加载页面并单击它们后,它们会下拉并显示通常为值的内容,但值是空的。

例如

---------------
|    Gender   |
---------------
|             |<-- Is supposed to show "M"
---------------
|             |<--Is supposed to shown "F"

我的代码

    <!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
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 list= document.getElementById("UserProfileGender");
        var choices=["M","F"];
        for(i=0;i<choices.length;i++)
        {
            var opt = document.createElement("option");
            opt.value= choices[i];
            list.appendChild(opt);
        }
    }

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


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



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

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


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

最佳答案

您还可以使用 new Option 动态添加选项.. 到 HTMLSelectElement 使用 add 方法...

 function AgeDropDown(){
        var list= document.getElementById("UserProfileAge");
        for(var i=1;i<100;i++)
        {
           var opt =new Option(i,i) ;
           list.add(opt);
        }
  }

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

我还注意到一件奇怪的事..在你的标记中......

<select id='UserProfileAge' name='UserProfileAge' onchange='AgeDropDown()'>

<select id='UserProfileGender' name='UserProfileGender' onchange='genderlist()'>

每次 select 的值发生变化时,您都会调用这两个函数。所以新选项将添加到 select 中。我不知道您为什么要这样做??

关于Javascript 下拉列表工作,但显示空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19477070/

相关文章:

javascript - 在 React 中实现 HTML5 Canvas 渐变

jquery - 我想根据鼠标悬停在不同按钮上相应地显示数据

javascript - 当参数传递 JQuery 时无法使函数为 true

jquery - 我可以在页面刷新时或离开页面时保留相同的 jQuery 选项卡吗?

javascript - 在幻灯片中添加淡入淡出效果 (Javascript)

javascript - 存储图像点击并回显链接

javascript - Jasmine toEqual 失败但打印两个对象是相同的

javascript - 从 IntelliJ 调试 Grails 应用程序的 JavaScript

javascript - 我怎样才能获得下拉选择的值并形成一个数字

javascript - d3.js 轴标签 - 颜色不变