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>





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM