项目中操作checkbox是经常碰到的,有了jquery后操作起来简单明了,代码如下:
- $(?function()?{??
- ??
- ????//全选??
- ????$("#selectAll").click(?function()?{??
- ????????$("input[name='send-mail']").each(?function()?{??
- ????????????$(this).attr("checked",?true);??
- ????????});??
- ????});??
- ????//?反选??
- ????$("#inverseAll").click(?function()?{??
- ????????$('input[name="send-mail"]').each(?function()?{??
- ????????????$(this).attr("checked",?!$(this).attr("checked"));??
- ????????});??
- ????});??
- ??
- ????//?取消全部??
- ????$("#deselectAll").click(?function()?{??
- ????????$("input[name='send-mail']").each(?function()?{??
- ????????????$(this).attr("checked",?false);??
- ????????});??
- ????});??
- ??
- ????//?选中的值??
- ????$("#sendMailAll").click(?function()?{??
- ????????var?selectedStr?=?"";??
- ????????var?$sendMail?=?$("input[name='send-mail']");??
- ????????$sendMail.each(?function()?{??
- ????????????if?($(this).attr("checked"))?{??
- ????????????????selectedStr?+=?$(this).val()?+?",";??
- ????????????}??
- ????????});??
- ????????if?($.trim(selectedStr)?==?"")?{??
- ????????????alert("请未选中任何数据!");??
- ????????????return?false;??
- ????????}??
- ???????????????alert(selectedStr?);??
- ??????????
- ????});??
- ??
- });??
?其页面部分代码如下:
- <div>??
- ???<s:iterator?value="page.result">??
- ????<tr>??
- ????????????<td><input?type="checkbox"?name="send-mail"?id="send-mail-id-${sendMailId}"?value="${sendMailId}"/></td>??
- ????</tr>???
- ????</s:iterator>??
- </div>??
- <div?id="footer-checkbox"??style="width:?100%;?margin-left:?260px;">??
- <input?type="button"?id="selectAll"?name="selectAll"?value="全选"?/>??
- <input?type="button"?id="inverseAll"?name="inverseAll"?value="反选"?/>??
- <input?type="button"?id="deselectAll"?name="deselectAll"?value="取消"?/>??
- <input?type="button"?id="sendMailAll"?name="sendMailAll"?value="发送"?/>??
- </div>??
?在使用前,记得将jquery引进
- <script?src="js/jquery.js"?type="text/javascript"></script>??
?
$("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"; //alert($(this).val()); }) alert(str); }) })?
?