Javascript DOM HTML document getElementsByName() Method loop

Introduction

Check all <input> elements with type="checkbox" in the document that have a name attribute with the value "animal":

Click the button to check all checkboxes that have a name attribute with the value "animal".

View in separate window

<!DOCTYPE html>
<html>
<body>

Cats:  <input name="animal" type="checkbox" value="Cats">
Dogs:  <input name="animal" type="checkbox" value="Dogs">

<button onclick="myFunction()">Test</button>

<script>
function myFunction() {//from   w  ww . j  a  v  a  2 s.  co m
  var x = document.getElementsByName("animal");
  var i;
  for (i = 0; i < x.length; i++) {
    if (x[i].type == "checkbox") {
      x[i].checked = true;
    }
  }
}
</script>

</body>
</html>



PreviousNext

Related