javascript:动态下拉菜单值

时间:2013-12-10 00:07:10

标签: javascript html

我想创建两个下拉表单,如果我在第一个菜单上选择一个项目,第二个菜单将显示相应的值。例如:如果我在第一个菜单上选择“水果”,那么第二个菜单将显示“apple”,“banana”等。它必须有值,所以我可以将它插入数据库。

html如下:

<select id="firstmenu" name="fruit">
<option value="apple">apple</option>
<option value="banana">banana</option>
</select>
<br/>
<select id="secondmenu" name="vegetable">
<option value="carrot">carrot</option>
<option value="celery">celery</option>
</select>

的JavaScript;我正在考虑使用类似的东西,但我不了解javascript

<script>
var a=document.forms["myform"]["fruit"].value;
var b=document.forms["myform"]["vegetable"].value;

if (a=="fruit")
{
...
}
</script>

有人可以给我一个代码示例吗?非常感谢帮助,谢谢。

4 个答案:

答案 0 :(得分:4)

那么,

如何使用jQuery?

http://jsfiddle.net/W4m9S/1/

    var items = [
    {
        name: '---',
        value:'',
        subitems: []
    },
    {
        name:'Fruit', 
        value: 'fruit', 
        subitems: [
            {name: 'Apple', value: 'apple'}, 
            {name:'Banana', value:'banana'}
        ]
    },
    {
        name: 'Vegetable',
        value: 'vegetable',
        subitems: [
            {name: 'Carrot', value:'carrot'},
            {name: 'Celery', value:'celery'}
        ]
    }
];


$(function(){
    var temp = {};

    $.each(items, function(){
        $("<option />")
        .attr("value", this.value)
        .html(this.name)
        .appendTo("#firstmenu");
        temp[this.value] = this.subitems;
    });

    $("#firstmenu").change(function(){
        var value = $(this).val();
        var menu = $("#secondmenu");

        menu.empty();
        $.each(temp[value], function(){
            $("<option />")
            .attr("value", this.value)
            .html(this.name)
            .appendTo(menu);
        });
    }).change();


});

答案 1 :(得分:3)

我使用Javascript创建了一个下拉菜单。然后,如果用户在主下拉菜单中选择了水果,我创建了“水果”选项,如果用户在主下拉菜单中选择了蔬菜,我创建了“蔬菜”选项。

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        function displayAccordingly() {

            //Call mainMenu the main dropdown menu
            var mainMenu = document.getElementById('mainMenu');

            //Create the new dropdown menu
            var whereToPut = document.getElementById('myDiv');
            var newDropdown = document.createElement('select');
            newDropdown.setAttribute('id',"newDropdownMenu");
            whereToPut.appendChild(newDropdown);

            if (mainMenu.value == "fruit") { //The person chose fruit

                //Add an option called "Apple"
                var optionApple=document.createElement("option");
                optionApple.text="Apple";
                newDropdown.add(optionApple,newDropdown.options[null]);

                //Add an option called "Banana"
                var optionBanana=document.createElement("option");
                optionBanana.text="Banana";
                newDropdown.add(optionBanana,newDropdown.options[null]);

            } else if (mainMenu.value == "vegetable") { //The person chose vegetabes

                //Add an option called "Spinach"
                var optionSpinach=document.createElement("option");
                optionSpinach.text="Spinach";
                newDropdown.add(optionSpinach,newDropdown.options[null]);

                //Add an option called "Zucchini"
                var optionZucchini=document.createElement("option");
                optionZucchini.text="Zucchini";
                newDropdown.add(optionZucchini,newDropdown.options[null]);

            }

        }
    </script>
</head>
    <body>
        <select id="mainMenu" onchange="displayAccordingly()">
        <option value="">--</option>
        <option value="fruit">Fruit</option>
        <option value="vegetable">Vegetable</option>
        </select>
        <div id="myDiv"></div>
    </body>

</html>

每次下拉菜单的值发生变化时,displayAccordingly()函数都会运行。它会创建一个新的下拉菜单,然后,如果主下拉菜单的值是水果,它会为新创建的下拉菜单添加水果选项,如果主下拉菜单的值是蔬菜,那么它会添加蔬菜选项到新创建的下拉菜单。

我希望这有帮助! :)

编辑:如果您更改下拉列表的值两次,则会创建2个下拉菜单。我添加了另一个变量来解决这个问题:

<!DOCTYPE html>
<html>
    <head>
    <script type="text/javascript">
    var created = 0;

        function displayAccordingly() {

            if (created == 1) {
                removeDrop();
            }

            //Call mainMenu the main dropdown menu
            var mainMenu = document.getElementById('mainMenu');

            //Create the new dropdown menu
            var whereToPut = document.getElementById('myDiv');
            var newDropdown = document.createElement('select');
            newDropdown.setAttribute('id',"newDropdownMenu");
            whereToPut.appendChild(newDropdown);

            if (mainMenu.value == "fruit") { //The person chose fruit

                //Add an option called "Apple"
                var optionApple=document.createElement("option");
                optionApple.text="Apple";
                newDropdown.add(optionApple,newDropdown.options[null]);

                //Add an option called "Banana"
                var optionBanana=document.createElement("option");
                optionBanana.text="Banana";
                newDropdown.add(optionBanana,newDropdown.options[null]);

            } else if (mainMenu.value == "vegetable") { //The person chose vegetabes

                //Add an option called "Spinach"
                var optionSpinach=document.createElement("option");
                optionSpinach.text="Spinach";
                newDropdown.add(optionSpinach,newDropdown.options[null]);

                //Add an option called "Zucchini"
                var optionZucchini=document.createElement("option");
                optionZucchini.text="Zucchini";
                newDropdown.add(optionZucchini,newDropdown.options[null]);

            }

            created = 1

        }

        function removeDrop() {
            var d = document.getElementById('myDiv');

            var oldmenu = document.getElementById('newDropdownMenu');

            d.removeChild(oldmenu);
        }
    </script>
    </head>
    <body>
        <select id="mainMenu" onchange="displayAccordingly()">
        <option value="">--</option>
        <option value="fruit">Fruit</option>
        <option value="vegetable">Vegetable</option>
        </select>
        <div id="myDiv"></div>
    </body>

</html>

答案 2 :(得分:2)

我想这个例子可能适合你的要求。我在dynamicdropdown()函数中为第二个选项设置了一些静态内容。没有问题你可以通过选项对象用你的动态内容来实现。例子

document.getElementById("subcategory").options[i] = new Option("key","value",false, false)

将是动态值的编号。

请参阅演示部分DEMO of dynamic drop down menu values

<html>
    <head>
        <title>Create dyanamic dropdown list in javascript</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <script language="javascript" type="text/javascript">
        function dynamicdropdown(listindex)
        {
            document.getElementById("subcategory").length = 0;
            switch (listindex)
            {
            case "fruits" :
                document.getElementById("subcategory").options[0]=new Option("Please select fruits","");
                document.getElementById("subcategory").options[1]=new Option("apple","apple");
                document.getElementById("subcategory").options[2]=new Option("banana","banana");
                document.getElementById("subcategory").options[3]=new Option("mangoes","mangoes");
                break;

            case "meats" :
                document.getElementById("subcategory").options[0]=new Option("Please select meats","");
                document.getElementById("subcategory").options[1]=new Option("pigs","pigs");
                document.getElementById("subcategory").options[2]=new Option("chicken","chicken");
                break;
            }
            return true;
        }
       </script>
    </head>
    <title>Dynamic Drop Down List</title>
    <body>
        <div class="category_div" id="category_div">Please specify food items:
        <select name="category" class="required-entry" id="category" onchange="javascript: dynamicdropdown(this.options[this.selectedIndex].value);">
            <option value="">Select food items</option>
            <option value="Php">fruits</option>
            <option value="Javascript">meats</option>
        </select>
        </div>
        <div class="sub_category_div" id="sub_category_div">Please select foods:
        <script type="text/javascript" language="JavaScript">
            document.write('<select name="subcategory" id="subcategory"><option value="">Please select foods</option></select>')
        </script>
        <noscript>
            <select name="subcategory" id="subcategory" >
            <option value="">Please select foods</option>
            </select>
        </noscript>
        </div>
    </body>
</html>

另请参阅更多详情:Reference

答案 3 :(得分:1)

我对你的问题感到有点困惑,但我刚为你写了两个示例:DEMO1DEMO2

DEMO1 - javascript

window.onload = function() {
    document.getElementById("firstmenu").addEventListener('change',function(e) {ha(e,'firstmenu','secondmenu');}, false);
};

function ha(e,first,second){
    var firstOptions = document.getElementById(first).options;
    var secondOptions = document.getElementById(second).options;
    for(var i = 1, j = firstOptions.length; i < j; i++) {
        secondOptions[i].value = firstOptions[i].value;
        secondOptions[i].text = firstOptions[i].text;
    }
};

DEMO2 - javascript

window.onload = function() {
   document.getElementById("firstmenu").addEventListener('change',function(e) {ha(e,'secondmenu');}, false);
   document.getElementById("secondmenu").addEventListener('change',function(e) {ha(e,'firstmenu');}, false);
};
function ha (e,id){
   var index = e.target.selectedIndex;
   document.getElementById(id).selectedIndex = index;
};

DEMO1和DEMO2具有相同的HTML:

<select id="firstmenu" name="City">
    <option value="--">--</option>
    <option value="NY">NY</option>
    <option value="LA">LA</option>
</select>
<br/>
<select id="secondmenu" name="zipCode">
    <option value="--">--</option>
    <option value="10001">10001(NY)</option>
    <option value="90001">90001(LA)</option>
</select>

希望这会对你有所帮助!!