2011-11-09 100 views
2

我想要在用戶已經檢查了一定數量的複選框之後,停止用戶檢查另一個複選框。即在檢查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(); 
     } 
    } 

    } 

}); 
+0

? – Salman

+0

哦,也許我誤解了這個問題......你希望新的複選框被選中,但之前或第一次選中的複選框被選中? –

回答

8

我可能誤解了這個問題...看到我的評論。

爲防止選擇,您可以撥打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'); 
    } 
}); 

DEMO

可替代地,設置this.checkedfalse。這甚至會阻止瀏覽器呈現複選標記。

DEMO

+0

謝謝Felix,它有幫助 – Sopo

0

一個單一的jQuery的功能你能分享你的HTML代碼多種形式

<form> 
<input type="checkbox" name="seg"><br> 
<input type="checkbox" name="seg" ><br> 
<input type="checkbox" name="seg"><br> 
<input type="checkbox" name="seg"><br> 
</form> 

<br><br><br><br><br> 

<form> 
    <input type="checkbox" name="seg1"><br> 
<input type="checkbox" name="seg1" ><br> 
<input type="checkbox" name="seg1"><br> 
<input type="checkbox" name="seg1"><br> 
</form> 

$('input[type="checkbox"]').click(function(event) { 
    if ($("input[name= "+ this.name +"]:checked").length > 3) { 
     event.preventDefault(); 
     alert('You\'re not allowed to choose more than 3 boxes'); 
    } 
});