在复选框取消检查事件中从HTML dropdownList中删除项目

时间:2012-07-18 17:33:13

标签: javascript html jsp

我有一个复选框列表和一个下拉列表。当我选中复选框时,我设法动态地将元素添加到下拉列表。

当我取消选中特定复选框时,如何从下拉列表中动态删除相应的项目。

这是我的代码

//<input type="checkbox" name="docCkBox" value="${document.documentName}" onclick="handleChange(this)"/>
// check box onclick event will call this function
   function handleChange(cb) {
         if (cb.checked)
    {

        // Create an Option object
        var opt = document.createElement("option");

        // Add an Option object to Drop Down/List Box
        document.getElementById("query_doc").options.add(opt);

        // Assign text and value to Option object
        opt.text = cb.value;
        opt.value = cb.value;


    }

    else{


//I want to remove a particuler Item when I uncheck the check-box
//by below method it will always remove the first element of the dropdown but not the corresponding element

 var opt = document.createElement("option");
 opt.text = cb.value;
 opt.value = cb.value;
 document.getElementById("query_doc").remove(opt);

 }


    }

2 个答案:

答案 0 :(得分:1)

您必须找到所需选项的索引并按索引删除。

答案 1 :(得分:1)

您需要访问select标记中已有的选项,而不是创建新选项。我会通过获取所有选项然后检查每个选项以查看它是否具有复选框的值来执行此操作。代码在else块中看起来像这样:

var opts = document.getElementById("query_doc").getElementsByTagName('option');
for(var i = 0; i < opts.length; i++){
    if(opts[i].value == cb.value){
        opts[i].parentNode.removeChild(opts[i]);
    }
}

我还没有测试过代码,但总体思路就在那里。