Jaykumar
Jaykumar

Reputation: 423

DOM javascript Form elements accessing

I have started javascript DOM manipulation, I come across an error maybe. Whenever I input in name field like jaykumar and press click me button .In demo, jaykumar comes and with in few microseconds go.

function myfunction() {
  var x = document.getElementById("myform").elements["fname"].value;
  document.getElementById("demo").innerHTML = x;
}
<form id="myform">
  name<input type="textbox" name="fname"> email
  <input type="textbox" name="email">
  <button onclick="myfunction()"> Click me</button>

</form>
<div id="demo"></div>

Upvotes: 0

Views: 115

Answers (1)

Jamiec
Jamiec

Reputation: 136239

A button inside a form's default behaviour is to submit the form. To change this make the button of type="button"

function myfunction() {
  var x = document.getElementById("myform").elements["fname"].value;
  document.getElementById("demo").innerHTML = x;
}
<form id="myform">
  name<input type="textbox" name="fname"> email
  <input type="textbox" name="email">
  <button type="button" onclick="myfunction()"> Click me</button>

</form>
<div id="demo"></div>

Upvotes: 1

Related Questions