0

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>

4
  • That’s because button creates a submit button by default, so the form submits, and that makes your page reload. Use type="button" to make it a click button instead. Commented Feb 18, 2021 at 10:22
  • it worked. But giving "[object HTMLInputElement]" instead of name "jaykumar" Commented Feb 18, 2021 at 10:27
  • @Jaykumar note in my edit of your question I added .value (I thought this was a typo but fixes the problem you stated). Also see my answer. Commented Feb 18, 2021 at 10:28
  • hi , if I want to access name and email with only var x =document.getElementById("myform").elements. Commented Feb 18, 2021 at 10:36

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.