JQuery开发获取复选框选中的个数
有这么一个需求,在多个复选框中最多选四个,并且复选框一旦选中之后,就不能再次选择。用JQuery实现不难,在这里简单记录一下,先看看下面的效果演示吧。
效果演示
你喜欢下面哪些网站,最多选4个。多过4个就没得选~
JQuery Code
<script type="text/javascript">
$(document).ready(function(){
$('input[type=checkbox]').click(function(){
$(this).attr('disabled','disabled');
if($("input[name='group1']:checked").length >= 4)
{
//alert("test");
$("input[name='group1']").attr('disabled','disabled');
}
});
$("#compute").click(function(){
$('input').live('click',function(){
//alert($('input:checked').length);
$("#show").html($('input:checked').length);
});
})
})
</script>
通过jQuery获取checkbox选中项的个数,需要用到jQuery的size()方法或length属性,下面的例子是通过length属性获得checkbox选中项的个数。
或者下面的代码也可以:
<script Language="JScript">
function check(){
var boxArray = document.getElementsByName('oBox');
var total = 0;
for(var i=0;i<boxArray.length;i++){
if(boxArray[i].checked){
total++;
}
}
if(total>0){
if(window.confirm('共选中'+total+'首歌,是否继续?')){
window.open('about:blank','SubWin','');
return true;
}
else{
return false;
}
}
else{
window.alert('没有选择!') ;
return false;
}
}
</script>
<form target="SubWin" onsubmit="return check();">
<input type="checkbox">歌曲一
<input type="checkbox">歌曲二
<input type="checkbox">歌曲三
<input type="button" value="看看">
</form>