'innerHTML disappearing quickly after displaying

I was trying to make a "find and replace" page and my code is working properly except that the resulting string is only displayed for a split second before it disappears and the form is reset

Here is the HTML

<body>
        <form>
            Text<textarea id="string"></textarea>
            <br>
            Find:<input type="text" id="keyword">
            <br>
            Replace with:<input type="text" id="replacewith">
            <button id="replace" onclick="findReplace()">Find and Replace</button>
        </form>
        <p id="result"></p>
    </body>

Here is the js

<script>
function findReplace(){
        var str = document.getElementById("string").value;
        var input = document.getElementById("keyword").value;
        var replaced = document.getElementById("replacewith").value;
            var x = str.replace(input, replaced);
            document.getElementById("result").innerHTML = x;
            }
        </script>


Solution 1:[1]

You will have to prevent the form from submitting, either by:
- Using findReplace as the submit eventHandler and calling event.preventDefault()
- Adding type="button" to the button element. (h/t radulfr)
- Adding onsubmit="return false" to your form element:

function findReplace() {
  var str = document.getElementById("string").value;
  var input = document.getElementById("keyword").value;
  var replaced = document.getElementById("replacewith").value;
  var x = str.replace(input, replaced);
  document.getElementById("result").innerHTML = x;
}
<form onsubmit="return false">
  Text<textarea id="string"></textarea>
  <br> Find:
  <input type="text" id="keyword">
  <br> Replace with:<input type="text" id="replacewith">
  <button id="replace" onclick="findReplace()">Find and Replace</button>
</form>
<p id="result"></p>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1