2012-07-18 44 views
0

我有一个复选框和一个下拉列表的列表。我设法添加元素动态下拉列表时,我检查复选框。删除项目从HTML dropdownList在复选框取消检查事件

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

这里是我的代码

//<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); 

} 


    } 

回答

1

您需要访问已在选择标记中的选项,而不是创建一个新选项。我会通过获取所有选项然后检查每个选项来查看它是否具有复选框的值。代码看起来像这样的内部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]); 
    } 
} 

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

1

你将不得不找到所需要的选项的索引,通过索引中删除。

相关问题