Sha*_*aoz 2 javascript checkbox jquery
我想在已经检查了一定数量的复选框后阻止用户检查另一个复选框.即,在选中3个复选框后,用户将无法再查看,并显示一条消息:"您不能选择超过3个方框."
我几乎在那里,但最后一个复选框仍在检查中,我不希望这样,我希望它不会被显示出来的消息.
我怎么做:
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();
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
我可能误解了这个问题......看到我的评论.
为了防止选择,您可以event.preventDefault()使用event参数调用和定义处理程序.
$('input[type="checkbox"]').click(function(event) {
if (this.checked && $('input:checked').length > 3) {
event.preventDefault();
alert('You\'re not allowed to choose more than 3 boxes');
}
});
Run Code Online (Sandbox Code Playgroud)
或者,设置this.checked为false.这甚至会阻止浏览器呈现复选标记.
| 归档时间: |
|
| 查看次数: |
4737 次 |
| 最近记录: |