1. 程式人生 > >多選框checkbox全選全不選和反選

多選框checkbox全選全不選和反選

沒有 index ntb -1 點擊事件 ner 空數組 一個 多個

在判斷多選框中的某一個是否被選中時,我們可以用checked的屬性

選中了就返回true,沒被選中就返回false;

這是html代碼:

<form action="#">
<label for="hobby">愛好:</label>
<label for="hobby1">
<input type="checkbox" name="hobby" id="hobby1">吃飯
</label>
<label for="hobby2">
<input type="checkbox" checked="" name="hobby" id="hobby2">睡覺
</label>
<label for="hobby3">
<input type="checkbox" name="hobby" id="hobby3">打豆豆
</label>
<button type="button" id="all">全選/全不選</button>
<button type="button" id="fan">反選</button>
</form>

接下來書寫js來進行全選/全不選 var checkbox=document.querySelectorAll("input");//獲取所有的checkbox var all=document.getElementById("all");//獲取全選按鈕
    var fan=document.getElementById("fan");//獲取反選按鈕
all.addEventListener("click",function () {//綁定點擊事件
var arr=[];//定義一個空數組
for(var i=0;i<checkbox.length;i++){
//console.log(checkbox[i].checked);
arr.push(checkbox[i].checked)//利用for循環將每個checkbox的checked屬性返回的true或者false存入數組arr中;
}
console.log(arr.indexOf(false));//判斷arr中是否包含false,返回-1則是不包含false,那麽所有的多選框都被選中,返回0,1,2等等;
     則是證明arr中包含false,則證明所有的checkbox中有沒有被選中的;
if(arr.indexOf(false)!="-1"){
for(var j=0;j<checkbox.length;j++){
checkbox[j].checked=true;//讓所有的多選框被選中
}
}else {
//alert(111);
for(var j=0;j<checkbox.length;j++){
checkbox[j].checked=false;//讓所有的多選框都沒有被選中選
}
}
})
接下來是書寫js讓反選實現  
fan.addEventListener("click",function () {
for(var i=0;i<checkbox.length;i++){
if(checkbox[i].checked==true){//先用for循環判斷每一個checkbox是否被選中,選中的讓其不被選中,不被選中的選中;
checkbox[i].checked=false;
}else {
checkbox[i].checked=true;
}
}
})

總結:在判斷多個復選框是否有沒有被選中時我們並不能直接進行判斷,此時我們可以使用創立一個新數組,然後利用for循環將每一個多選框是否被選中的返回結果存入數組中,然後跟根據

indexof判斷數組中是否有false,如果有則返回下標,沒有則返回-1;判斷過後再進行全選全不選。
  

多選框checkbox全選全不選和反選