Arbaz
Arbaz

Reputation: 11

I'm not able to print js variable in html

When I try printing a js variable in a h1 tag it's just printing for 2 milliseconds and disappears afterwards.

function validateForm() {
  // alert("hello");
  var name = document.myform.name.value;
  document.getElementById("a1").innerHTML = name;
  // document.myform.write.value= name; 
}
<html>

<head>

  <title>
    js 1
  </title>
</head>

<body>

  <form name="myform" onSubmit="return validateForm();">
    Name<input type="text" name="name"><br> Password <input type="text" name="password"><br><br>

    <h1 id="a1"></h1>
    <input type="submit" value="submit"><br>
  </form>
</body>

</html>

I want the output to print the name the user enters and it should be visible until the second time the user enters another name.

Upvotes: 0

Views: 223

Answers (3)

Mamun
Mamun

Reputation: 68933

This is because the button type is being submit your from is submitted immediately. If you want to stay in the same page,you can either change the type of the button from submit to input.

 <input type="button" value="submit"><br>

OR: Use event.preventDefault(); to neutralize the event.

<script type="text/javascript">
  function validateForm(){
     // alert("hello");
      var name=document.myform.name.value;
      document.getElementById("a1").innerHTML = name  ;
     // document.myform.write.value= name; 
     event.preventDefault();
  }
</script>
<form name="myform" onSubmit="return validateForm();">
  Name<input type="text" name="name"><br>
  Password <input type="text" name="password"><br><br>

  <h1 id="a1"></h1>
  <input type="submit" value="submit"><br>
</form>

Upvotes: 1

Stranger in the Q
Stranger in the Q

Reputation: 3898

In your validateForm function you can return false to prevent form from submitting and page from reloading.

function validateForm() {
   document.getElementById("a1").innerHTML = document.myform.name.value;
   return false;
}
<form name="myform" onsubmit="return validateForm();">
Name<input type="text" name="name"><br>
Password <input type="text" name="password"><br><br>
<h1 id="a1"></h1>
<input type="submit" value="submit"><br>
</form>

Upvotes: 1

AKX
AKX

Reputation: 168913

Your form is being submitted immediately, so the page reloads.

Return false from your event handler to prevent that from happening.

function validateForm() {
    var name = document.myform.name.value;
    document.getElementById("a1").innerHTML = name;
    return false;
}

Upvotes: 0

Related Questions