ASP.NET- JS - 按住shift多選打勾 checkBox- Shift多選打勾checkBox - ASP+JAVASCRIPT
按住shift一次可多勾選checkBox的功能在純前端非常常見
無奈遇到的系統是Asp.net
前端的checkBox是由後端撈資料庫動態產生的
所以必須將js結合asp才能夠實現這個功能
網路上都找不到相關的程式碼
只好自己手刻
這邊就分享程式碼
checkBox動態產生 先打勾一個 按住Shift 再按另一個checkBox
則中間checkBox都會被勾選(若已勾選的則取消勾選)
全程式皆為js
請貼在aspx前端頁面並且建議在checkbox之後
注意
動態物件產生的id前面都會相同,最後則是數字遞增
所以程式碼中「動態物件產生的id」指的是數字之前的字串
例如動態產生的物件id為 abc_0、abc_1、abc_2
則程式碼中"動態物件產生的id" 請填入 "abc_"
程式碼
<script type="text/javascript"> var shiftON = false; //儲存shift是否被按下 var IDs = new Array(); //紀錄開始或結束的checkboxID var IDe = new Array(); //紀錄開始或結束的checkboxID var IDs; var IDe; //判斷鍵盤點選 window.document.onkeydown = OnBodyKeyDow; //判斷鍵盤放開 window.document.onkeyup = OnBodyKeyDowNO; // window.οnlοad = OnBodyKeyDo; //判斷shift是否按下 shift代號為16 function OnBodyKeyDow() { if ((window.event.keyCode == 16)) { shiftON = true; } }//判斷shift是否放開 shift代號為16 function OnBodyKeyDowNO() { if ((window.event.keyCode == 16)) { shiftON = false; } } $(document).ready(function () { //判斷checkbox是否被點選 $("input").click(function () { IDe = $(this).attr('id').split("動態物件產生的id") //如果shift按下 if (shiftON) { //console.log(IDs); //console.log(IDe); $("input").each(function () { // console.log($(this).attr('id')); var NewArray = new Array(); var NewArray = $(this).attr('id').split("動態物件產生的id"); //將全部checkboxID分離末位代碼後存進NewArray //如果IDe[1](動態產生ID的末位數字index)的數字轉為10進位 //大於IDs[1](動態產生ID的末位數字index)的數字轉為10進位 //則將NewArray中末碼(產生的index)介於IDe[1]與IDs[1]之間的全部選起 if (parseInt(IDe[1], 10) > parseInt(IDs[1], 10)) { if (parseInt(NewArray[1], 10) > parseInt(IDs[1], 10) && parseInt(NewArray[1], 10) < parseInt(IDe[1], 10)) { //判斷本來是否有打勾,本來已勾的則取消,未勾的則打勾 if ($(this).attr("checked")) { $(this).attr("checked", false); } else { $(this).attr("checked", true); } // console.log($(this).attr('id')); } } else { if (parseInt(NewArray[1], 10) > parseInt(IDe[1], 10) && parseInt(NewArray[1], 10) < parseInt(IDs[1], 10)) { if ($(this).attr("checked")) { $(this).attr("checked", false); } else { $(this).attr("checked", true); } // console.log($(this).attr('id')); } } }); } else { //若未按下shift 則每次選擇checkbox時都要更新id IDs = $(this).attr('id').split("動態物件產生的id_") } }); }); </script>
留言
張貼留言