JavaScript小例子:复选框全选
JavaScript小例子:复选框全选
这只是一个小例子,很简单,但是这个功能还是很常用的:
实现后效果如图:
JavaScript代码:
<script type="text/javascript"> function selectAll() { var allMails = document.getElementsByName("allMails")[0]; var mails = document.getElementsByName("email"); if(allMails.checked) { for(var i = 0; i < mails.length; ++i) { mails[i].checked = true; } } else { for(var i = 0; i < mails.length; ++i) { mails[i].checked = false; } } } </script>
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> <script type="text/javascript"> function selectAll() { var allMails = document.getElementsByName("allMails")[0]; var mails = document.getElementsByName("email"); if(allMails.checked) { for(var i = 0; i < mails.length; ++i) { mails[i].checked = true; } } else { for(var i = 0; i < mails.length; ++i) { mails[i].checked = false; } } } </script> </head> <body> 全选<input type="checkbox" onclick="selectAll()" name="allMails"><br><br><br> <input type="checkbox" name="email"><br> <input type="checkbox" name="email"><br> <input type="checkbox" name="email"><br> <input type="checkbox" name="email"><br> <input type="checkbox" name="email"><br> <input type="checkbox" name="email"><br> <input type="checkbox" name="email"><br> </body> </html>
参考资料
圣思园张龙老师Java Web培训视频。