Javascript DOM HTML document forms Collection iterate elements from first form

Introduction

Using the elements collection together with document.forms to get the value of each element in the form:

Click the button to display the value of each element in the form.

View in separate window

<!DOCTYPE html>
<html>
<body>
<form action="/action_page.php">
  First name: <input type="text" name="fname" value="CSS"><br>
  Last name: <input type="text" name="lname" value="HTML"><br>
  City: <input type="text" name="fname" value="Duckburg"><br>
  <input type="submit" value="Submit">
</form>/* w ww .j av a2 s .  com*/
<button onclick="myFunction()">Test</button>

<p id="demo"></p>

<script>
function myFunction() {
  var x = document.forms[0];
  var txt = "";
  var i;
  for (i = 0; i < x.length; i++) {
    txt = txt + x.elements[i].value + "<br>";
  }
  document.getElementById("demo").innerHTML = txt;
}
</script>

</body>
</html>



PreviousNext

Related