Autoplay flags in javascript

I have several checkboxes on my page and a Select All button. I want all elements on the checked page to be checked when the select button is clicked. This is the javascript code I tried:

<script>
    function selectall() {
        for (var i = 0; i < document.getElementsByName("ch").length; i++) {
            document.getElementsByName(ch[i]).checked = true;
        }
    }
</script>
      

Run codeHide result


And here's the html:

<form action="analize.php" method="POST" enctype="multipart/form-data">
    <input type="button" onclick="selectall()" value="SELECT ALL" />
    <input type="checkbox" name="ch[]" value="a" align="MIDLE" />
    <input type="checkbox" name="ch[]" value="b" align="MIDLE" />
    <input type="checkbox" name="ch[]" value="c" align="MIDLE" />
</form>
      

Run codeHide result


But it doesn't work. What is the problem?
+3


source to share


1 answer


The name

target element's ch[]

not attribute ch

. It .getElementsByName(ch[i])

should also be .getElementsByName('ch[]')[i]

.

for (var i = 0; i < document.getElementsByName("ch[]").length; i++) {
    document.getElementsByName('ch[]')[i].checked = true;
}

      



You can also cache NodeList

, which is more efficient than requesting the DOM on each iteration:

var nodeList = document.getElementsByName("ch[]");
for (var i = 0; i < nodeList.length; i++) {
    nodeList[i].checked = true;
}

      

+3


source







All Articles