根据另一个选择填充一个下拉菜单 [英] Populate one dropdown based on selection in another

查看:97
本文介绍了根据另一个选择填充一个下拉菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用javascript根据下拉列表A中的选择更改下拉列表B的内容。没有涉及的数据库查询 - 我事先知道B的内容应该在A中作出选择。我发现了一些使用AJAX的例子,但是因为没有涉及数据库查询,所以没有必要。任何人都可以指点一些示例代码来说明如何做到这一点?

I need to change the contents of dropdown B based on the selection in dropdown A using javascript. There are no db queries involved--I know beforehand what the contents of B should be given the choice in A. I have found some examples using AJAX, but since there is no db query involved that's not necessary. Can anyone point me to some example code for how to do this?

推荐答案

<script type="text/javascript">
     function configureDropDownLists(ddl1,ddl2) {
    var colours = ['Black', 'White', 'Blue'];
    var shapes = ['Square', 'Circle', 'Triangle'];
    var names = ['John', 'David', 'Sarah'];

    switch (ddl1.value) {
        case 'Colours':
            ddl2.options.length = 0;
            for (i = 0; i < colours.length; i++) {
                createOption(ddl2, colours[i], colours[i]);
            }
            break;
        case 'Shapes':
            ddl2.options.length = 0; 
        for (i = 0; i < shapes.length; i++) {
            createOption(ddl2, shapes[i], shapes[i]);
            }
            break;
        case 'Names':
            ddl2.options.length = 0;
            for (i = 0; i < names.length; i++) {
                createOption(ddl2, names[i], names[i]);
            }
            break;
            default:
                ddl2.options.length = 0;
            break;
    }

}

    function createOption(ddl, text, value) {
        var opt = document.createElement('option');
        opt.value = value;
        opt.text = text;
        ddl.options.add(opt);
    }
</script>

然后像这样调用它:

And then call it like this:

<select id="ddl" onchange="configureDropDownLists(this,document.getElementById('ddl2'))">
<option value=""></option>
<option value="Colours">Colours</option>
<option value="Shapes">Shapes</option>
<option value="Names">Names</option>
</select>

<select id="ddl2">
</select>

这篇关于根据另一个选择填充一个下拉菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆