您的位置:首页 > Web前端 > JQuery

JQuery获取被选中复选框checkbox的个数

2011-03-18 00:00 531 查看
有这么一个需求,在多个复选框中最多选四个,并且复选框一旦选中之后,就不能再次选择。用JQuery实现不难,在这里简单记录一下,先看看下面的效果演示吧。


效果演示

你喜欢下面哪些网站,最多选4个。多过4个就没得选~




www.nowamagic.net


www.google.com


www.163.com


www.qq.com


www.g.cn


www.zhengzeyan.net


news.163.com


mail.163.com








$(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);
});
})
})


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" name="oBox">歌曲一
<input type="checkbox" name="oBox">歌曲二
<input type="checkbox" name="oBox">歌曲三
<input type="button" value="看看">
</form>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: