Limit number of checkboxes to be selected, jQuery [closed]

空扰寡人 提交于 2020-03-17 02:58:30

问题


A simpler version of this question has already been posted, but I'm having some difficulty.

Say I have 5 checkboxes:

  • None
  • Apple
  • Banana
  • Orange
  • Pear

The user is allowed to select two checkboxes, but if "None" is chosen, they can only select one.

Is that possible at all?


回答1:


Try to play with this example:

var checked = [],
$check = $('.check').change(function() {
    if (this.value == -1 && this.checked) {
        $check.not(this).prop('disabled', true).prop('checked', false);
        checked = [];
    }
    else {
        $check.prop('disabled', false);
        checked.push(this);
        checked = $(checked)
        checked.prop('checked', false).slice(-2).prop('checked', true);
    }
});

http://jsfiddle.net/q7Dve/



来源:https://stackoverflow.com/questions/16337625/limit-number-of-checkboxes-to-be-selected-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!