Use getElementsByName to achieve multiple selection, inverse selection, and full selection

code show as below:

<html>

    <head>

        <script type="text/javascript">

            function checkAll(){

                var hobbies=document.getElementsByName("hobby");

                for(var i=0;i<3;i++){

                    hobbies[i].checked=true;

                }

            }

            function checkNo(){

                var hobbies=document.getElementsByName("hobby");

                for(var i=0;i<3;i++){

                    hobbies[i].checked=false;

             }

            }

            function checkRe(){

                var hobbies=document.getElementsByName("hobby");

                for(var i=0;i<3;i++){

                    if(hobbies[i].checked){

                        hobbies[i].checked=false;

                    }else{

                        hobbies[i].checked=true;

                    }

             }

            }

        </script>

    </head>

    <body>

        <input type="checkbox" name="hobby" value="java"/>java

        <input type="checkbox" name="hobby" value="c"/>c

        <input type="checkbox" name="hobby" value="js"/>js

        <button οnclick="checkAll()">Select All</button>

        <button οnclick="checkNo()">No check</button>

        <button οnclick="checkRe()">反选</button>

    </body>

</html>

Problem encountered : when using for loop traversal, the loop body is not executed during execution. Finally, it was discovered that i was not assigned an initial value.

The variables in js are weak types, that is, the types can be changed. The assigned value determines the type of the variable. A variable that has not been assigned an initial value is undefined.

Guess you like

Origin blog.csdn.net/defined_/article/details/118440570