jQuery限制“下拉列表检查”选择

我正在使用带有dropdownchecklist项目的jquery。 这是我配置selectbox的代码。

jQuery('#selectbox').dropdownchecklist({ width: 120, maxDropHeight: 100, firstItemChecksAll: false, emptyText: 'Select' }); 

我想限制只有2个选择的选择。 如果用户选择2个选项,则所有其他项目将禁用以进行选择。 我该怎么做?

更新:我找到了最简单的方法

  function Selectbox_limit(jidList) { var jids = ''; var counter = 0; for(var i=0; i= 2) { jidList.options[i-1].selected = false; jQuery("#selectbox").dropdownchecklist("destroy"); jQuery("#selectbox option").attr('disabled','disabled'); jQuery("#selectbox option:selected").attr("disabled",""); jQuery('#selectbox').dropdownchecklist({ _propeties_ }); return; } else if(counter < 2) { jQuery("#selectbox").dropdownchecklist("destroy"); jQuery("#selectbox option").attr("disabled",""); jQuery('#selectbox').dropdownchecklist({ _propeties_ }); return; } } 

dropdownchecklist将活动类添加到复选框,以便您可以像这样使用它:

 $('.active').change(function () { var num = 0; $('.active:checked').each(function () { num++; }); if(num >= 2) { $('.active:checked').attr("disabled", "disabled"); $('.active:checked').each(function () { $(this).removeAttr(); }); } else { $('.active').removeAttr("disabled", "disabled"); } }); 

这是一个带有限制的jQuery下拉列表的示例

 onItemClick: function(checkbox, selector){ var justChecked = checkbox.prop("checked"); var checkCount = (justChecked) ? 1 : -1; for( i = 0; i < selector.options.length; i++ ){ if ( selector.options[i].selected ) checkCount += 1; } if ( checkCount > 3 ) { alert( "Limit is 3" ); throw "too many"; } } 

你可以这样做

 var $b = $('input[type=checkbox]'); if(($b.filter(':checked').length)>2){ $b.attr("disabled", true); } 

或者你可以使用

 $(':checkbox:checked").length $(":checkbox").filter(':checked').length 

希望它有所帮助。