Javascript DOM HTML Form elements Collection get by item

Introduction

item(index)

Get the value of the first element, which has index of 0, in a form:

var x = document.getElementById("myForm").elements.item(0).value;

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

View in separate window

<!DOCTYPE html>
<html>
<body>

<form id="myForm" action="/action_page.php">
  First name: <input type="text" name="fname" value="CSS"><br>
  Last name: <input type="text" name="lname" value="HTML"><br>
  <input type="submit" value="Submit">
</form>//from   www  . j  a va  2s  .  c  o m
<button onclick="myFunction()">Test</button>

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

<script>
function myFunction() {
  var x = document.getElementById("myForm").elements.item(0).value;
  document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>



PreviousNext

Related