<select id='optgroup' class="searchable" multiple='multiple'>
<option value='11'>Maths</option>
<option value='12'>Physics</option>
<option value='13'>Chemistry</option>
<option value='14'>Biology</option>
<option value='15'>Computer Science</option>
<option value='16'>Accounts</option>
<option value='17'>Commerce</option>
<option value='18'>Business Maths</option>
<option value='19'>Economics</option>
<option value='20'>History</option>
</select>
此演示我使用 MultipleSelect [http://loudev.com/] Jquery插件。
我想为可选项目设置限制。 例如只选择任意4项。
$('#optgroup').multiSelect({ selectableOptgroup: true ,
selectableHeader: "<input type='text' class='form-control category-seletable ' autocomplete='off' placeholder='Search'>",
selectionHeader: "<input type='text' class='form-control category-selection' autocomplete='off' placeholder='Search'>",
});
我尝试了 this 。但不适合我。
答案 0 :(得分:2)
您可以使用afterSelect()
回调和deselect()
来执行此操作。
this.$selectionUl
是包含所有选项的正确区域display: none
(是的,所有选项),这些选中的选项会将display
设置为list-item
并添加一个类{ {1}}。因此,如果所选选项的数量大于.ms-selected
,那么我们可以通过$(this.$selectionUl).find('.ms-selected').length
计算所选数字,然后4
刚刚选择的数字。
deselect
&#13;
$("#optgroup").multiSelect({
selectableOptgroup: true,
selectableHeader: "<input type='text' class='form-control category-seletable ' autocomplete='off' placeholder='Search'>",
selectionHeader: "<input type='text' class='form-control category-selection' autocomplete='off' placeholder='Search'>",
afterSelect: function(data) {
// data is an array within the values of the options just being selected
if ($(this.$selectionUl).find('.ms-selected').length > 4) {
// deselect the item with the value given in parameter(data)
// the value can be either an array of string or a string
$("#optgroup").multiSelect('deselect', data);
console.log('You can only select 4 items!!')
}
}
});
&#13;