Checkbox 限制选择个数,其余不可选

利用官方例子写的一个demo

1.WXML

<checkbox-group>
    <label class="checkbox padding-sm fl"
        wx:for="{{items}}"
        wx:key="r_ability_checkbox"
        wx:for-item="a"
        id="{{index}}"
        bindtap="{{!a.canCheck?'checkChange':''}}"
    >
    <checkbox class="round theme-r-color s7"
        checked="{{a.checked}}"
        disabled="{{a.canCheck}}" />{{a.value}}
    </label>
</checkbox-group>

2.JS

Page({
    data: {
        items: [
            { name:'USA', value:'美国'},
            { name:'CHN', value:'中国'},
            { name:'BRA', value:'巴西'},
            { name:'JPN', value:'日本'},
            { name:'ENG', value:'英国'},
            { name:'TUR', value:'法国'},
        ],
        checkNum: 0,
        max:false,
        maxCheckedNum: 3
    },
    checkChange(e) {
        let id = e.currentTarget.id;
        this.data.items[id].checked = !this.data.items[id].checked;
        this.data.checkNum = this.data.items[id].checked ? this.data.checkNum + 1 : this.data.checkNum - 1;
        this.checkMax(this.data.checkNum);
    },
    checkMax(num) {
        const maxNum = this.data.maxCheckedNum;
        const items = this.data.items;
        if (num == maxNum) {
            var status = true;
        } else if (num < maxNum && this.data.max) {
            var status = false;
        }
        if (status != undefined) {
            this.data.max = status;
            for (var i = 0; i < items.length; i++) {
                if (!items[i].checked) items[i].canCheck = status;
            }
            this.setData({
                items: items
            })
        }
    },
})

如有任何意见亦请告知

 

 

 

 
posted @ 2019-08-17 15:04  dearyang  阅读(102)  评论(0)    收藏  举报