jQuery 对复选框的操作

范例代码如下:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>我是复选框测试页</title>
<script type="text/javascript" src="<%=request.getContextPath()%>/res/js/jquery-2.1.1.js"></script>
<script type="text/javascript"> $(function(){ //全选 $("#btn1").bind("click",function(){ $("[name = checkItem]:checkbox").attr("checked",true); }); //全不选 $("#btn2").click(function(){ $("[name = checkItem]:checkbox").attr("checked",false); }); //反选 $("#btn3").click(function(){ $("[name = checkItem]:checkbox").each(function(){ $(this).attr("checked",!$(this).attr("checked")); }); }); //输出复选框被选中的个数 $("#btn4").click(function(){ alert($("input[name = checkItem]:checked").length);//方法一 }) }) </script>
</head>
<body>
<h1>复选框功能</h1>
<hr>
兴趣爱好:
<div>
<input type="checkbox" name="checkItem" value="篮球"/>篮球
<input type="checkbox" name="checkItem" value="羽毛球"/>羽毛球
<input type="checkbox" name="checkItem" value="乒乓球"/>乒乓球
<input type="checkbox" name="checkItem" value="游泳"/>游泳
</div>

<div>
<input id = "btn1" type="button" value="全选"/>
<input id = "btn2" type="button" value="全不选"/>
<input id = "btn3" type="button" value="反选"/>
<input id = "btn4" type="button" value="输出复选框被选中的个数"/>
</div>
</body>
</html>

你可能感兴趣的:(jquery)