简体   繁体   English

选择多个:如何选择/取消选择(JavaScript)

[英]Select Multiple: How to select/unselect (Javascript)

1)I have no Javascript knowledge. 1)我不懂Javascript。

2)I am using a select2 (multiple select) bootstrap form. 2)我使用的是select2(多次选择)引导程序表格。 3)I want to deselect the other options of a group if I click in one option of the corresponding group. 3)如果我单击相应组的一个选项,则要取消选择该组的其他选项。

3.1)eg: If option values "2" and "6" are selected and then I click options "1" and "5", it should automatically deselects options "2" and "6". 3.1)例如:如果选择了选项值“ 2”和“ 6”,然后单击选项“ 1”和“ 5”,它将自动取消选择选项“ 2”和“ 6”。

Thanks. 谢谢。

  <div align = "center" class="form-group"> <label>Filtros</label> <select name ="Filtros" id = "Filtros" class="form-control select2" multiple="multiple" data-placeholder="Selecione os Filtros" style="width: 100%;"> <optgroup label="IBC"> <option value="1">IBC_ALL</option> <option value="2">IBC_SIM</option> <option value="3">IBC_NAO</option> <option value="4">IBC_Nao_Mostrar</option> <optgroup label="CROT"> <option value="5">CROT_ALL</option> <option value="6">CROT_SIM</option> <option value="7">CROT_NAO</option> <option value="8">CROT_Nao_Mostrar</option> </select> </div> 

It works fine on me. 对我来说效果很好。 If you check multiple choices from different categories, it automatically deselecting another choices from another category. 如果您检查来自不同类别的多个选项,它将自动从另一个类别中取消选择另一个选项。
Note: Not working when user use SHIFT key. 注意:当用户使用SHIFT键时不起作用。

<div align = "center" class="form-group">
<label>Filtros</label>
<select name ="Filtros" id = "Filtros" class="form-control select2" multiple="multiple" data-placeholder="Selecione os Filtros"
        style="width: 100%;">

<optgroup label="IBC" parent="1">
  <option value="1" childof="1">IBC_ALL</option>
  <option value="2" childof="1">IBC_SIM</option>
  <option value="3" childof="1">IBC_NAO</option>
  <option value="4" childof="1">IBC_Nao_Mostrar</option>

<optgroup label="CROT" parent="2">
  <option value="5" childof="2">CROT_ALL</option>
  <option value="6" childof="2">CROT_SIM</option>
  <option value="7" childof="2">CROT_NAO</option>
  <option value="8" childof="2">CROT_Nao_Mostrar</option>

</select>
</div>

<script>
var selected = {
    1:[],
    2:[]
}
var last_selected = 1;
document.getElementById('Filtros').addEventListener('click',function(e){
var parent = e.target.getAttribute('childof');

if( e.target.selected )
{
    selected[parent].push(e.target);

  for( var i=0; i < selected[parent].length; i++ )
  {
    var elem = selected[parent][i];

    if(!elem.selected)
      selected[parent].splice(i,1);
  }

  if( parent != last_selected )
  {
    for( var i=0; i < selected[last_selected].length; i++ )
    {
      var elem = selected[last_selected][i];
      elem.selected = false;
    }
  }

  last_selected = parent;
}
});
</script>

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

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