use*_*119 2 html javascript jquery twitter-bootstrap
我正在使用Bootstrap Multiselect显示年份列表,其中所选年份的最大数量可以是4.如果选择了4年,则禁用所有未选择的年份; 如果一年未被选中进行计数3,则再次启用所有年份.
(该插件项目的最新提交是添加启用/禁用功能,但我不认为这是针对个别选择元素的 - https://github.com/davidstutz/bootstrap-multiselect/issues/171)
我的HTML:
<select id="slYears" class="multiselect" multiple="multiple">
<option value="1" disabled="disabled">2009</option>
<option value="2" selected="selected">2010</option>
<option value="3" selected="selected">2011</option>
<option value="4" selected="selected">2012</option>
<option value="5" selected="selected">2013</option>
</select>
Run Code Online (Sandbox Code Playgroud)
我的JavaScript(第一次尝试):
$('#slYears').change(function () {
var arr = $(this).val().toString().split(',');
if (arr.length >= 4) {
$('#slYears option').each(function () {
if (!$(this).is(':selected')) {
$(this).prop('disabled', true);
}
});
}
else {
$('#slYears option').each(function () {
$(this).prop('disabled', false);
});
}
});
Run Code Online (Sandbox Code Playgroud)
然后我尝试使用一些插件的方法和示例.我尝试使用'全选'示例启用所有,我尝试使用'onchange'事件,但没有一个工作.
这是jsfiddle:http://jsfiddle.net/389Af/1/(注意我在上面的JS之前粘贴了插件JS)
好的我想出了一个解决方案.我在插件的当前主分支中添加了一个演示.见这里:http://davidstutz.github.io/bootstrap-multiselect/#further-examples.代码如下所示.在此代码中select
具有ID example37
:
$('#example37').multiselect({
onChange: function(option, checked) {
// Get selected options.
var selectedOptions = $('#example37 option:selected');
if (selectedOptions.length >= 4) {
// Disable all other checkboxes.
var nonSelectedOptions = $('#example37 option').filter(function() {
return !$(this).is(':selected');
});
var dropdown = $('#example37').siblings('.multiselect-container');
nonSelectedOptions.each(function() {
var input = $('input[value="' + $(this).val() + '"]');
input.prop('disabled', true);
input.parent('li').addClass('disabled');
});
}
else {
// Enable all checkboxes.
var dropdown = $('#example37').siblings('.multiselect-container');
$('#example37 option').each(function() {
var input = $('input[value="' + $(this).val() + '"]');
input.prop('disabled', false);
input.parent('li').addClass('disabled');
});
}
}
});
Run Code Online (Sandbox Code Playgroud)
一些解释:selectedOptions
是当前所选选项的数组.如果选择了4个或更多选项,则禁用所有其他复选框(不禁用不可见选择内的选项).如果选择的选项少于4个,则再次启用所有复选框.
归档时间: |
|
查看次数: |
22363 次 |
最近记录: |