0

I have a button with a JavaScript event handler, trying to make a change in the document object model on click. It makes that change, but immediately reverts it; clicking the button causes the text to change, but only for an instant before changes back. Why is it changing back? How can I stop that happening?

var button_variable_name = document.getElementById("changeText");
  button_variable_name.addEventListener("click", function() {
    document.querySelector('#test').textContent="Replace the text";

  });
<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8">
<title>blank</title>

</head>
<body>

<form> 

<input type="text" id="a" />
<input type="text" id="b" />
<input type="text" id="c" />
<button id="changeText" > button </button>

</form>
<p id="test"> test text </p>

</body>
</html>
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
rwallace
  • 31,405
  • 40
  • 123
  • 242
  • 3
    The button is inside a form, which it's submitting. Move it outside the form (which isn't doing anything anyway) and it works fine. – jonrsharpe Feb 25 '20 at 22:41

1 Answers1

3

A button inside a form is defaulted used as submit button and so when you click it, the form is submitted and so the page reload; you just need to specify that that button isn't a submit button:

<button id="changeText" type="button"> button </button>

Note the type="button", default is type="submit"

Alberto Sinigaglia
  • 12,097
  • 2
  • 20
  • 48