我想要在用戶已經檢查了一定數量的複選框之後,停止用戶檢查另一個複選框。即在檢查3個複選框之後,用戶不能再檢查,並且消息顯示「你不能選擇多於3個盒子」。在jQuery或JavaScript中檢查了多個複選框之後,停止檢查複選框
我幾乎在那裏,但最後一個複選框仍在檢查,我不希望這樣,我希望它沒有選中與消息出現。
如何做到這一點:
var productList = $('.prod-list'),
checkBox = productList.find('input[type="checkbox"]'),
compareList = $('.compare-list ul');
productList.delegate('input[type="checkbox"]', 'click', function() {
var thisElem = $(this),
thisData = thisElem.data('compare'),
thisImg = thisElem.closest('li').find('img'),
thisImgSrc = thisImg.attr('src'),
thisImgAlt = thisImg.attr('alt');
if (thisElem.is(':checked')) {
if ($('input:checked').length < 4) {
compareList.append('<li data-comparing="' + thisData + '"><img src="' + thisImgSrc + '" alt="'+ thisImgAlt +'" /><li>');
} else {
$('input:checked').eq(2).attr('checked', false);
alert('You\'re not allowed to choose more than 3 boxes');
}
} else {
var compareListItem = compareList.find('li');
for (var i = 0, max = compareListItem.length; i < max; i++) {
var thisCompItem = $(compareListItem[i]),
comparingData = thisCompItem.data('comparing');
if (thisData === comparingData) {
thisCompItem.remove();
}
}
}
});
? – Salman
哦,也許我誤解了這個問題......你希望新的複選框被選中,但之前或第一次選中的複選框被選中? –