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
JavaScript
x
12
12
1
<body>
2
<form>
3
Text<textarea id="string"></textarea>
4
<br>
5
Find:<input type="text" id="keyword">
6
<br>
7
Replace with:<input type="text" id="replacewith">
8
<button id="replace" onclick="findReplace()">Find and Replace</button>
9
</form>
10
<p id="result"></p>
11
</body>
12
Here is the js
JavaScript
1
10
10
1
<script>
2
function findReplace(){
3
var str = document.getElementById("string").value;
4
var input = document.getElementById("keyword").value;
5
var replaced = document.getElementById("replacewith").value;
6
var x = str.replace(input, replaced);
7
document.getElementById("result").innerHTML = x;
8
}
9
</script>
10
Advertisement
Answer
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:
JavaScript
1
7
1
function findReplace() {
2
var str = document.getElementById("string").value;
3
var input = document.getElementById("keyword").value;
4
var replaced = document.getElementById("replacewith").value;
5
var x = str.replace(input, replaced);
6
document.getElementById("result").innerHTML = x;
7
}
JavaScript
1
8
1
<form onsubmit="return false">
2
Text<textarea id="string"></textarea>
3
<br> Find:
4
<input type="text" id="keyword">
5
<br> Replace with:<input type="text" id="replacewith">
6
<button id="replace" onclick="findReplace()">Find and Replace</button>
7
</form>
8
<p id="result"></p>