Search code examples
javascriptformsdomgetelementbyid

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>


Solution

  • 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>