- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <title>全选全不选反选取值</title>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <script src1="script/jquery-1.4.3.js" type="text/javascript"></script>
- <script type="text/javascript">
- $(function () {
- $("#selAll").click(function () { //":checked"匹配所有的复选框
- $("#div1 :checkbox").attr("checked", true); //"#div1 :checked"之间必须有空格checked是设置选中状态。如果为true则是选中fo否则false为不选中
- });
- $("#unselAll").click(function () {
- $("#div1 :checkbox").attr("checked", false);
- });
- //理解用迭代原理each(function(){})
- $("#reverse").click(function () {
- $("#div1 :checkbox").each(function () {
- $(this).attr("checked",!$(this).attr("checked")); //!$(this).attr("checked")判断复选框的状态:如果选中则取反
- });
- });
- $("#submit").click(function (){
- var items= $("input:checkbox:checked");
- if (items>0) {
- alert("您选中了"+items.length+"个项目");
- var checked=[];
- $("input:checkbox:checked").val();
- $("input:checkbox:checked").each(function() {
- console.log("---",$(this));
- // checked.push($(this).attr("value"));//获取value值
- checked.push($(this).next().text());//获取显示文本的值
- });
- alert(checked);
- }else{
- alert("您还没选择!");
- }
- });
- });
- </script>
- </head>
- <body>
- <div id="div1">
- <input type="checkbox" /><label>歌曲1</label><br />
- <input type="checkbox" /><label>歌曲2</label><br />
- <input type="checkbox" /><label>歌曲3</label><br />
- <input type="checkbox" /><label>歌曲4</label><br />
- <input type="checkbox" /><label>歌曲5</label><br />
- <input type="checkbox" /><label>歌曲6</label><br />
- <input type="checkbox" /><label>歌曲7</label><br />
- <input type="button" id="selAll" value="全选" />
- <input type="button" id="unselAll" value="全不选" />
- <input type="button" id="reverse" value="反选 " />
- <input type="button" id="submit" value="提交"/>
- </div>
- </body>
- </html>
- //该片段来自于http://www.codesnippet.cn/detail/271120137519.html
来源: http://www.codesnippet.cn/detail/271120137519.html