The example in this article describes how to implement full selection, non-selection and inverse selection of checkbox in js. Share it with everyone for your reference. The specific analysis is as follows:
1. Ideas:
1. Get elements
2. Add click events to select all, unselect or inverse selection
3. Use for loop checkbox
4. Set checked in the checkbox to true to select all
5. Set checked in the checkbox to false to deselect it
6. Through if judgment, if checked is true and the selected state is set, set checked to false and unselected. If checked is false and unselected, set checked to true and selected.
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 /> </div>
3. js code:
<script> window.onload=function(){ var sele=document.getElementById('sele');//获取全选 var unsele=document.getElementById('setinterval');//获取不选 var clear=document.getElementById('clear');//获取反选 var checkbox=document.getElementById('checkboxs');//获取div var checked=checkbox.getElementsByTagName('input');//获取div下的input //全选 sele.onclick=function(){ for(i=0;i<checked.length;i++){ checked[i].checked=true } } //不选 unsele.onclick=function(){ for(i=0;i<checked.length;i++){ checked[i].checked=false } } //反选 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 design.