1

Why the only button placed inside the form displays stable message from its javascript function?

function myFunction() {
  document.getElementById("demo").innerHTML = "Hello Dear Visitor!";
}
<form onsubmit="myFunction()">
  <p> buttons inside the form does unstable result display</p>
  <input type="submit" class="buton" value="Submit" onclick="myFunction()">
  <button onclick="myFunction()"> Inside Form </button>
</form>
<hr>
<p> button outside the form does good result display</p>
<button onclick="myFunction()"> Outside Form </button>

<p id="demo"></p>
Anurag Srivastava
  • 14,077
  • 4
  • 33
  • 43

1 Answers1

1

Clicking on a button causes the form to submit and navigates to a new page, which causes the message displayed to appear only for a short time before the page refreshes or navigates away. As a result, you may not see the message consistently.

To prevent the form submission and retain the message, you need to prevent the default form submission behavior. You can do this by adding return false; at the end of the myFunction() function or by using event.preventDefault().

Demo:

function myFunction(event) {
  document.getElementById("demo").innerHTML = "Hello Dear Visitor!";
  event.preventDefault();
}
<form onsubmit="myFunction(event)">
  <p> buttons inside the form does unstable result display</p>
  <input type="submit" class="buton" value="Submit" onclick="myFunction(event)"> 
  
  <button onclick="myFunction(event)"> Inside Form </button>
</form>
<hr>

<p id="demo"></p>
Mamun
  • 66,969
  • 9
  • 47
  • 59
  • Thanx a lot Mamun, sometimes I need a kick, but on a many tut pages this issue is omitted, which is absent when you practice the topic.. – user2279628 Jul 26 '23 at 11:37