PaulR PaulR - 9 days ago 6
HTML Question

avoid reload page after innerHTML update with function call

When changing a html element with a function using innerHTML, the html element changes, but immediately the page reloads and the element is set back to his original value.
How can this be avoided ?

I realise that I am probably missing something very essential and feel a little bit embarrassed launching this question. But, I googled around for this problem and I could not find an answer. If someone could take a minute to put me on the right track in this forest of html, javascript, css an php where I try to find my way, I would very much appreciate.

<!DOCTYPE html>
<html>
<head>
<title>Question stackoverflow</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div>
<p id="test"> This should be changed after button click </p>
<form>
<button onclick="test()">Refresh</button>
</form>
</div>
<script>
function test(){
document.getElementById("test").innerHTML = "replaced";
}
</script>
</body>
</html>

Answer

Add type="button" in the button.

<button type="button" onclick="test()">Refresh</button>

By default, the type of the button is considered as submit, thus submits the form on clicking the button.