Javascript DOM HTML Form elements Collection get by elements

Introduction

Get the value of the element with name="fname" in a form:

var x = document.getElementById("myForm").elements.namedItem("fname").value;

Click button to display the value of the element with name="fname" 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 w  w  w  .  j  a  v a2s  . co m
<button onclick="myFunction()">Test</button>

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

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

</body>
</html>



PreviousNext

Related