JavaScript +将项目添加到下拉列表中

时间:2010-04-12 15:40:56

标签: javascript drop-down-menu

我的JSP页面中有两个下拉列表

1. lstA
     test1
     test2
     test3
     test4

2. lstB

现在选择lstA时,我想将lstA的所有项目填充到lstB中,除了select选项之外,lstA的内容也应该保持不变。

我怎样才能做到这一点?

我试图这样做,但是从lstA中删除了一些随机的项目,这是非常有线的。

3 个答案:

答案 0 :(得分:8)

你的回答几乎是正确的。

需要注意的事项:您需要在添加之前清除客户端列表,否则您最终会在其上添加越来越多的项目,并且需要在将选项添加到客户端列表之前克隆该选项,因为节点可以任何时候只存在于父母一方。

这已经过测试并且对我有用:

<html><body>
<script language="javascript">
function populateClient() {
     var serverList = document.getElementById("dropdown1");
     var clientList = document.getElementById("dropdown2");

     clientList.options.length = 0; // this removes existing options

     for (var i = 0; i <= serverList.options.length; i++) {
         if (!serverList.options[i].selected) {
             clientList.options.add(serverList.options[i].cloneNode(true)); // cloneNode here
         }
     }
 }
</script>

<select id="dropdown1" onchange="populateClient()">
    <option value="value1">value1</option>
    <option value="value2">value2</option>
    <option value="value3">value3</option>
    <option value="value4">value4</option>
    <option value="value5">value5</option>
</select>
<select id="dropdown2">
</select>
</body></html>

答案 1 :(得分:1)

试试这个

<script type="text/javascript">
    function AddItem()
    {
        // Create an Option object       
        var opt = document.createElement("option");        

        // Assign text and value to Option object
        opt.text = "New Value";
        opt.value = "New Value";

        // Add an Option object to Drop Down List Box
        document.getElementById('<%=DropDownList.ClientID%>').options.add(opt);
    }
<script />

该值将附加到下拉列表中。

答案 2 :(得分:0)

function populateClient(selectItem, clientItem) {
             var serverList = selectItem;
             for(var i = 1; i <= serverList.options.length; i++) {
                 if (!serverList.options[i].selected)
                     clientItem.options.add(serverList.options[i]);
             }
         }

其中selectItem和clientItem是下拉列表。

当我这样做时,一些数据被随机填充到clientItem中,并且selectItem中的一些项被删除。

相关问题