jQuery limit “Dropdown Check List” selects

2019-07-28 05:21发布

问题:

I'm using jquery with dropdownchecklist item. this is my code to config selectbox.

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

I want to limit the select for only 2 selects. If the user select 2 options all others item will disable for selecting. How can I do it?

Update: I found the easiest way to do this

 function Selectbox_limit(jidList) {
    var jids = '';
    var counter = 0;
for(var i=0; i<jidList.options.length; i++) {
    if(jidList.options[i].selected == true)
        counter++;

    if(counter >= 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; 
    }
}

回答1:

The dropdownchecklist add the class active to the check boxes so you can use it like this:

$('.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"); 
     }
});


回答2:

here is a sample of a jQuery Dropdown Check List with limit

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";
  }
}


回答3:

You can do it by this

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

or you can use

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

hope it help.