JS----checked----checked选中和未选中的获取




全选、全不选、反选功能


html代码

<form action="" id="oForm" name="myForm">
        <input type="checkbox" name="hobby" id="basket" value="basket">篮球<Br>
        <input type="checkbox" name="hobby" id="zuqiu" value="zuqiu" >足球<Br>
        <input type="checkbox" name="hobby" id="paiqiu" value="paiqiu">排球<Br>
        <input type="checkbox" name="hobby" id="wqiu" value="wqiu">网球<Br>
        <input type="checkbox" name="hobby" id="biqiu" value="biqiu">壁球<Br>
        <input type="checkbox" name="hobby" id="bpq" value="bpq">乒乓球<Br>
        <input type="checkbox" name="hobby" id="ymq" value="ymq">羽毛球<Br>
        <input type="button" name="all" id="all" value='全选' onclick="setVal(1)">
        <input type="button" name="allNo" id="allNo" value='全不选' onclick="setVal(0)">
        <input type="button" name="noCheck" id="noCheck" value='反选' onclick="setVal(-1)">
  </form>




JS代码

function setVal(iNum){
        var aForm = document.getElementById("myForm");
        var aArr = aForm.hobby;   
        for(var i=0;i<aArr.length;i++){        
            if( iNum<0 ){
                aArr[i].checked = !aArr[i].checked;   
            }else{
                aArr[i].checked = iNum;
            }           
        }
    }



设置选中

下边两种写法没有任何区别 只是少了些代码而已
<input id="cb1" type="checkbox" checked />
<input id="cb2" type="checkbox" checked="checked" />


jquery赋值checked的几种写法:
所有的jquery版本都可以这样赋值:
// $("#cb1").attr("checked","checked");
// $("#cb1").attr("checked",true);


jquery1.6+:prop的4种赋值:
// $("#cb1").prop("checked",true);//很简单就不说了哦
// $("#cb1").prop({checked:true}); //map键值对
// $("#cb1").prop("checked",function(){
return true;//函数返回true或false
});
//$("#cb1").prop("checked","checked");



为什么input checkbox有 checked='checked'还是没选中
如果用jQuery1.6+来写的话:
建议使用
$(element).prop('checked', true/false);
而不是
$(element).attr('checked', true/false);
其实也就相当于要使用:
element.checked = true/false;
而并不是
element.setAttribute('checked', true/false/'checked');





jquery判断checked的三种方法

.attr('checked'):   //看版本1.6+返回:"checked"或"undefined" ;1.5-返回:true或false
.prop('checked'): //16+:true/false
.is(':checked'):    //所有版本:true/false//别忘记冒号哦




jQuery获取未选中的checkbox

 $('input[type=checkbox]').not("input:checked");  




jQuery获取选中的checkbox

$('input[type=checkbox]:checked');






jquery官网checked的用法

http://api.jquery.com/checked-selector/





DataTable翻页checked部分代码

内容太多需要勾选时,我们需要做翻页,但是翻页要记录之前的页面勾选了哪些,需要借助input来记录。html代码如下:


   
   
  1. <%@ page language= "java" import= "java.util.*" pageEncoding= "UTF-8"%>
  2. <%@ taglib prefix= "c" uri= "http://java.sun.com/jsp/jstl/core" %>
  3. <%@ taglib uri= "http://java.sun.com/jsp/jstl/fmt" prefix= "fmt"%>
  4. <%@ taglib prefix= "shiro" uri= "http://shiro.apache.org/tags" %>
  5. <%@ taglib uri= "http://java.sun.com/jsp/jstl/functions" prefix= "fn"%>
  6. <%@ taglib uri= "com.data.web.view.function" prefix= "cf"%>
  7. <%
  8. String path = request.getContextPath();
  9. String basePath = request.getScheme()+ "://"+request.getServerName()+ ":"+request.getServerPort()+path+ "/";
  10. %>
  11. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  12. <html xmlns= "http://www.w3.org/1999/xhtml">
  13. <head>
  14. </head>
  15. <body>
  16. <link rel= "stylesheet" href= "/assets/js/dataTables/dataTables.responsive.min.css"></link>
  17. <div id= "page-wrapper">
  18. <div id= "page-inner">
  19. <div class= "col-md-12">
  20. <h1 class= "page-head-line"> 参考文献 <button id= "btnSave" type= "button" class= "btn btn-success pull-right" data-loading-text= "Saving...">保 存</button></h1>
  21. <form class= "form-inline col-sm-11" id= "search_form">
  22. <input class= "form-control" type= "hidden" name= "plate" value= "8">
  23. </form>
  24. </div>
  25. <input class= "form-control" type= "hidden" id= 'checkList' >
  26. <div class= "row">
  27. <div class= "col-md-12">
  28. <div class= "panel panel-default">
  29. <div class= "panel-heading">参考文献列表</div>
  30. <div class= "panel-body">
  31. <div class= "table-responsive">
  32. <table
  33. class= "table table-striped table-bordered responsive table-hover"
  34. id= "table" cellspacing= "0" width= "100%">
  35. <thead>
  36. <tr>
  37. <th width= "8%" class= "min-mobile-l">期刊名</th>
  38. <th width= "20%" class= "desktop">标题</th>
  39. <th width= "10%" class= "min-mobile-l">作者</th>
  40. <th width= "10%" class= "min-mobile-l">摘要</th>
  41. <th width= "10%" class= "min-mobile-l">引用</th>
  42. </tr>
  43. </thead>
  44. </table>
  45. </div>
  46. </div>
  47. </div>
  48. </div>
  49. </div>
  50. </div>
  51. </div>
  52. </body>
  53. </html>
  54. <!-- /. WRAPPER -->
  55. <!-- JS Scripts-->
  56. <!-- jQuery Js -->
  57. <script src= "/assets/js/jquery-1.10.2.js"></script>
  58. <!-- Bootstrap Js -->
  59. <script src= "/assets/js/bootstrap.min.js"></script>
  60. <!-- Metis Menu Js -->
  61. <script src= "/assets/js/jquery.metisMenu.js"></script>
  62. <!-- CUSTOM SCRIPTS -->
  63. <script src= "/assets/js/custom.js"></script>
  64. <!-- Morris Chart Js
  65. <script src= "assets/js/morris/raphael-2.1.0.min.js"></script>
  66. <script src= "assets/js/morris/morris.js"></script>-->
  67. <!-- Custom Js
  68. <script src= "assets/js/custom-scripts.js"></script>-->
  69. <!-- DATA TABLE SCRIPTS -->
  70. <script src= "/assets/js/dataTables/jquery.dataTables.js"></script>
  71. <script src= "/assets/js/dataTables/dataTables.bootstrap.js"></script>
  72. <script src= "/plugins/bootstrap-datepicker/js/bootstrap-datepicker.min.js"></script>
  73. <script src= "/plugins/bootstrap-datepicker/locales/bootstrap-datepicker.zh-CN.min.js"></script>
  74. <script type= "text/javascript">
  75. $(function(){
  76. var checkedIdsOld = "<c:forEach items="${ancestry.documents} " var="item ">${ item.id }|</c:forEach>";
  77. $( "#checkList").val(checkedIdsOld);
  78. refreshTable();
  79. bindCheckListChange();
  80. $( '#btnSave').click(function(){
  81. $( this).button( 'loading');
  82. var allValue = $( "#checkList").val();
  83. allValue = allValue.substring( 0, allValue.length - 1);
  84. allValue = allValue.replace(/[ ]/g, "");
  85. var checkedIds = allValue.split( "|");
  86. console.log(checkedIds);
  87. $.postJSON( '/docAssociate',
  88. checkedIds,
  89. function(res){
  90. $( '#btnSave').button( 'reset');
  91. location.href = '/test}'
  92. if(!res.code){
  93. alert( '保存失败');
  94. }
  95. }
  96. );
  97. });
  98. });
  99. function bindCheckListChange() {
  100. $( '#table').on( 'change', '.checkbox',function(){
  101. var allValue = $( "#checkList").val();
  102. if (typeof($( this).attr( "checked")) == "undefined") {
  103. //改变前是 未选中,则变为选中,把值增加到checkList中
  104. $( this).attr( "checked", 'true');
  105. if (!contains(allValue, $( this).attr( "value"), false)) {
  106. allValue += $( this).attr( "value") + "|";
  107. $( "#checkList").val(allValue);
  108. console.log(allValue);
  109. }
  110. } else {
  111. //改变前是选中,则变为未选中,把值从checkList中删除
  112. $( this).removeAttr( "checked");
  113. if (contains(allValue, $( this).attr( "value"), false)) {
  114. var rstr = $( this).attr( "value") + "|";
  115. allValue = allValue.replace(rstr, "");
  116. $( "#checkList").val(allValue);
  117. console.log(allValue);
  118. }
  119. }
  120. })
  121. }
  122. function refreshTable() {
  123. $( '#table')
  124. .DataTable(
  125. {
  126. responsive : true,
  127. lengthChange : false,
  128. serverSide : true, //分页,取数据等等的都放到服务端去
  129. stateSave : true,
  130. searching : false,
  131. processing : true, //载入数据的时候是否显示“载入中”
  132. bDestroy : true,
  133. pageLength : 2, //首次加载的数据条数
  134. ordering : false, //排序操作在服务端进行,所以可以关了。
  135. language : {
  136. processing : "载入中", //处理页面数据的时候的显示
  137. paginate : { //分页的样式文本内容。
  138. previous : "上一页",
  139. next : "下一页",
  140. first : "第一页",
  141. last : "最后一页"
  142. },
  143. zeroRecords : "没有内容", //table tbody内容为空时,tbody的内容。
  144. //下面三者构成了总体的左下角的内容。
  145. info : "第 _PAGE_/_PAGES_页 共 _TOTAL_条记录", //左下角的信息显示,大写的词为关键字。
  146. infoEmpty : "第 _PAGE_/_PAGES_页 共 _TOTAL_条记录", //筛选为空时左下角的显示。
  147. infoFiltered : "" //筛选之后的左下角筛选提示(另一个是分页信息显示,在上面的info中已经设置,所以可以不显示),
  148. },
  149. "columnDefs" : [ {
  150. "defaultContent" : "",
  151. "targets" : "_all"
  152. } ],
  153. "ajax" : { //类似jquery的ajax参数,基本都可以用。
  154. type : "post", //后台指定了方式,默认get,外加datatable默认构造的参数很长,有可能超过get的最大长度。
  155. url : "/referenceDocument/listData",
  156. dataSrc : "data", //默认data,也可以写其他的,格式化table的时候取里面的数据
  157. data : function(d) { //d 是原始的发送给服务器的数据,默认很长。
  158. var param = {}; //因为服务端排序,可以新建一个参数对象
  159. param.start = d.start; //开始的序号
  160. param.length = d.length; //要取的数据的
  161. var formData = $( "#search_form")
  162. .serializeArray(); //把form里面的数据序列化成数组
  163. formData.forEach(function(e) {
  164. param[e.name] = e.value;
  165. });
  166. return param; //自定义需要传递的参数。
  167. }
  168. },
  169. "columns" : [
  170. {
  171. "data" : "author",
  172. "class" : "text-center"
  173. },
  174. {
  175. "data" : "title",
  176. "class" : "text-center",
  177. },
  178. {
  179. "data" : "name",
  180. "class" : "text-center",
  181. },
  182. {
  183. "data" : "summary",
  184. "class" : "text-center",
  185. },
  186. {
  187. "class": "text-center",
  188. "render": function(data, type, row, position) {
  189. var allValue = $( "#checkList").val();
  190. allValue = allValue.substring( 0, allValue.length - 1);
  191. allValue = allValue.replace(/[ ]/g, "");
  192. var checkedIds = allValue.split( "|");
  193. return '<input type="checkbox" class="checkbox" value="' + row.id + '" ' + (checkedIds && checkedIds.indexOf(row.id) > - 1 ? 'checked="checked"' : '') + '">';
  194. }
  195. }
  196. ]
  197. });
  198. }
  199. /**
  200. *string:原始字符串
  201. *substr:子字符串
  202. *isIgnoreCase:忽略大小写
  203. */
  204. function contains(string, substr, isIgnoreCase) {
  205. if (isIgnoreCase) {
  206. string = string.toLowerCase();
  207. substr = substr.toLowerCase();
  208. }
  209. var startChar = substr.substring( 0, 1);
  210. var strLen = substr.length;
  211. for (var j = 0; j < string.length - strLen + 1; j++) {
  212. if (string.charAt(j) == startChar) //如果匹配起始字符,开始查找
  213. {
  214. if (string.substring(j, j + strLen) == substr) //如果从j开始的字符与str匹配,那ok
  215. {
  216. return true;
  217. }
  218. }
  219. }
  220. return false;
  221. }
  222. /**
  223. * like $.getJSON, Load JSON-encoded data from the server using a POST HTTP
  224. * request.
  225. */
  226. $.postJSON = function(url, data, fnSuccess, fnError) {
  227. $.ajax({
  228. url: url,
  229. type: "POST",
  230. dataType: "json",
  231. cache: false,
  232. contentType: "application/json",
  233. data: JSON.stringify(data),
  234. success: function(result) {
  235. fnSuccess && (fnSuccess(result) || 1) || (typeof result.code != 'undefined' && !result.code && tip(result.error || '更新失败...'));
  236. },
  237. error: function(err) {
  238. if (err.status == 401) {
  239. return tip(err.status + ' ' + err.statusText + ', 当前会话已失效,请去新窗口 <a target="_blank" href="/login?from=' + encodeURIComponent(location.href) + '">登陆</a> 后继续操作!', 60000);
  240. }
  241. fnError && (fnError.apply($, Array.prototype.slice.call(arguments)) || 1) || tip(err.status + ' ' + err.statusText);
  242. }
  243. });
  244. };
  245. </script>




猜你喜欢

转载自www.cnblogs.com/jpfss/p/9699476.html
今日推荐