在复选框取消选中事件中从HTML下拉列表中删除项目

remove items from HTML dropdownList at checkbox un-check event

本文关键字:HTML 下拉列表 删除项目 事件 取消 复选框      更新时间:2023-11-06

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

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

这是我的代码

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

    }

您需要访问select标记中已经存在的选项,而不是创建新的选项。我会得到所有的选项,然后检查每个选项,看看它是否有复选框的值。在其他块中,代码看起来像这样:

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]);
    }
}

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

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