This article describes the method of JS to implement checkbox selection, non-select and anti-select. Share it for your reference. The specific analysis is as follows:
1. Ideas:
1. Get elements
2. Add click event to select all without selecting them
3. Loop checkbox with for
4. Set checkbox checked to true to select all
5. Set checkbox checked to false to achieve no selection
6. Judging by if, if checked is true, set checked to false and unselected state, and if checked is false and unselected state, set checked to true and unselected state.
2. HTML code:
<input type="button" value="全选" id="sele"/><input type="button" value="不选" id="setinterval"/><input type="button" value="反选" id="clear"/><div id="checkboxs"> <input type="checkbox"/><br /> <input type="checkbox"/><br /> <input type="checkbox"/><br /> <input type="checkbox"/><br /> <input type="checkbox"/><br /> <input type="checkbox"/><br /> <input type="checkbox"/><br /> <input type="checkbox"/><br /> <input type="checkbox"/><br /> <input type="checkbox"/><br /> <input type="checkbox"/><br /> <input type="checkbox"/><br /> <input type="checkbox"/><br /> <input type="checkbox"/><br /> <input type="checkbox"/><br /> <input type="checkbox"/><br /> <input type="checkbox"/><br /> <input type="checkbox"/><br /> <input type="checkbox"/><br /> <input type="checkbox"/><br /> <input type="checkbox"/><br />
3. js code:
<script>window.onload=function(){ var sele=document.getElementById('sele');//Get all var unsele=document.getElementById('setinterval');//Get unselected var clear=document.getElementById('clear');//Get anti-selected var checkbox=document.getElementById('checkboxs');//Get div var checked=checkbox.getElementsByTagName('input');//Get input under div//Select all sele.onclick=function(){ for(i=0;i<checked.length;i++){ checked[i].checked=true } }//Don't select unsele.onclick=function(){ for(i=0;i<checked.length;i++){ checked[i].checked=false } }//Unselect clear.onclick=function(){ for(i=0;i<checked.length;i++){ if(checked[i].checked=true){ checked[i].checked=false } else{ checked[i].checked=true } }}</script>I hope this article will be helpful to everyone's JavaScript programming.