如何为Bootstrap Form Select配置最大选择限制

时间:2019-07-10 05:53:12

标签: javascript dropdown bootstrap-selectpicker

我必须为启用多个选择的表单选择控件添加一个限制

如何配置最大选择限制?

<select id="region" class="selectpicker" multiple data-live-search="true" onChange="getState(this.value);" data-title="Region">
  <option value="Africa">Africa</option>
  <option value="Asia-Pacific">Asia-Pacific</option>
  <option value="Europe">Europe</option>
  <option value="India">India</option>
  <option value="Mena">Mena</option>
  <option value="North America">North America</option>
  <option value="South America">South America</option>
</select>

1 个答案:

答案 0 :(得分:0)

如果您使用的是Vanilla JS:

function selectLimiter(selectElement, maximum, minimum){
  var o = selectElement.options, l = o.length, oldChange = selectElement.onchange;
  var max = maximum === undefined ? l : maximum;
  var min = minimum === undefined ? 0 : minimum; 
  for(var i=0,ops=[]; i<l; i++){
    ops[i] = o[i].selected;
  }
  selectElement.onchange = function(){
    if(oldChange)oldChange();
    var q = this.selectedOptions.length;
    if(q < min || q > max){
      for(var i=0; i<l; i++){
        o[i].selected = ops[i];
      }
    }
    else{
      for(var i=0; i<l; i++){
        ops[i] = o[i].selected;
      }
    }
  }
}
selectLimiter(document.getElementById('region'), 2);
<select id='region' title='Region' class='selectpicker' multiple='mulitple' size='7'>
  <option value='Africa'>Africa</option>
  <option value='Asia-Pacific'>Asia-Pacific</option>
  <option value='Europe'>Europe</option>
  <option value='India'>India</option>
  <option value='Mena'>Mena</option>
  <option value='North America'>North America</option>
  <option value='South America'>South America</option>
</select>

否则,它就是重复项。