简体   繁体   English

Javascript清除多选框

[英]Javascript clear multi select boxes

I've 2 multiselect boxes one is with values and the second one is empty. 我有2个多选框,一个是带值的,第二个是空的。 When I choose option from the left and click arrow button it takes the value to the second one. 当我从左侧选择选项并单击箭头按钮时,它将值取为第二个。 My question is how can I clear it by a function in button and restore these values I mean get back the value to the first one and clear the second one. 我的问题是如何通过button的函数清除它并恢复这些值我的意思是将值返回到第一个并清除第二个值。 I tried like that but it does not work. 我试过这样,但它不起作用。

myOptions.options.length = 0;
myOptions.options[0] = new Option("", "");

Here is a simple add/remove model using a click listener and two buttons. 这是一个使用点击监听器和两个按钮的简单添加/删除模型。

In the example we look at the selectedOptions collection and move them. 在示例中,我们查看selectedOptions集合并移动它们。

 const moveFrom = (source) => { let target = (source === 'main') ? '#target' : '#main'; target = document.querySelector(target); Array.from(document.querySelector(`#${source}`).selectedOptions).forEach(opt => { target.add(opt); }); }; document.addEventListener('click', (e) => { if(e.target.matches('#add')) { moveFrom('main'); } if(e.target.matches('#remove')){ moveFrom('target'); } }); 
 div { display: inline-block; } select { display: inline-block; width: 50px; } 
 <div> <select id="main" size="5" multiple="true"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> </div> <div> <button id="add">Add</button> <button id="remove">remove</button> </div> <div> <select id="target" size="5" multiple="true"> </select> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM