开发者

JQuery Dropdown checklist uncheck checkbox if there are a certain number of checkboxes already checked

开发者 https://www.devze.com 2023-03-04 01:18 出处:网络
I\'m working with JQuery Dropdown checklist. I\'d like when I\'vee checked a certain number of options (three for example) if I check a fourth one it doesn\'t check.

I'm working with JQuery Dropdown checklist. I'd like when I'vee checked a certain number of options (three for example) if I check a fourth one it doesn't check.

I've seen there is: onItemClick: function(checkbox) {}. Inside this function is there any way of knowing the number of checked elements ? I haven't got it.

I'v开发者_如何学Pythone also tried with change event of the underlying html select but no luck (I get something but not totally the functionality I need).


Perhaps a simpler solution would be something like:

$('input:checkbox').click(
    function(){
        if ($('input:checkbox:checked').length >= 3) {
           return false;
        }
    });

JS Fiddle demo.

Though the above is posted due to my unfamiliarity with the onItemClick function. Possibly, and hopefully, others might offer more pertinent advice as regards that aspect of the question.


onItemClick: function(checkbox) {} The onItemClick option defines a callback function invoked when the user clicks on any item. It is called with a single argument which is the dynamically generated checkbox element. The callback can 'reject' the click by throwing any error.

So something like this should work (untested):

onItemClick: function(checkbox) {
    if($("#ddcl-YOURSELECTID-ddw input:checked").length >=3){
        throw "TOO MANY!";
    }
} 

You'll also want to check the checkbox passed in to see if it's checked or not before rejecting it, since you don't want to disallow unchecking. I'm not sure though what state the passed checkbox is in (before or after click), so you'll need to just test that and add the appropriate condition into the if.

0

精彩评论

暂无评论...
验证码 换一张
取 消