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

标签 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);

 }


    }

最佳答案

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

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

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

关于javascript - 在复选框取消选中事件中从 HTML dropdownList 中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11547088/

相关文章:

javascript - 在 Typescript 中将文本分配给局部变量

javascript - 模型中具有父/子关系的 Knockout JS 单选按钮问题

php - 我从零开始的第一个 WordPress 主题。在 functions.php 文件中排队样式表

javascript - 使用 Bootstrap 的可折叠菜单

java - 使用 dsp include in atg 包含动态页面

javascript - 单击按钮时更新元素的可见性

javascript - 下划线模板不会加载 Model.id,在打印 <% console.log(Model.id) %> 时它显示为未定义

javascript - 如何找到代表其实际 html 元素的 React DOM 节点?

HTML 页面在打印时被裁剪

java - 如何在Jsp中循环自引用类?