单选框的全选、全不选、部分选和获取选中值
程序员文章站
2023-12-22 19:26:40
...
本实例展示了web程序中一组单选框的选择情况。
项目代码结构如图所示:
index.jsp代码如下所示:
运行效果如下图所示:
项目代码结构如图所示:
index.jsp代码如下所示:
<%@ page language="java" import="java.util.*" 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"> <html> <head> <base href="<%=basePath%>"> <title>test jquery</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <script type="text/javascript" src="javascript/jquery-1.4.js"> </script> <script type="text/javascript"> $("document").ready(function(){ $("#btn1").click(function(){ $("[name='checkbox']").attr("checked","true"); }); $("#btn2").click(function(){ $("[name='checkbox']").removeAttr("checked"); }); $("#btn3").click(function(){ $("[name='checkbox']:even").attr("checked","true"); }); $("#btn4").click(function(){ $("[name='checkbox']").each(function(){ if($(this).attr("checked")){ $(this).removeAttr("checked"); }else{ $(this).attr("checked","true"); } }); }); $("#btn5").click(function(){ var str = ""; $("[name='checkbox']:checked").each(function(){ str+=$(this).val()+"\r\n"; }); window.alert(str); }); }); </script> </head> <body> <input type="button" id="btn1" value="全选"> <input type="button" id="btn2" value="取消全选"> <input type="button" id="btn3" value="选中所有奇数"> <input type="button" id="btn4" value="反选"> <input type="button" id="btn5" value="获取选中的所有值"> <br/><br/> <input type="checkbox" name="checkbox" value="checkbox1">checkbox1 <input type="checkbox" name="checkbox" value="checkbox2">checkbox2 <input type="checkbox" name="checkbox" value="checkbox3">checkbox3 <input type="checkbox" name="checkbox" value="checkbox4">checkbox4 <input type="checkbox" name="checkbox" value="checkbox5">checkbox5 <input type="checkbox" name="checkbox" value="checkbox6">checkbox6 </body> </html>
运行效果如下图所示: