我必须为启用多个选择的表单选择控件添加一个限制
如何配置最大选择限制?
<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>
答案 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>
否则,它就是重复项。