PaulR PaulR - 1 year ago 72
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>
<title>Question stackoverflow</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<p id="test"> This should be changed after button click </p>
<button onclick="test()">Refresh</button>
function test(){
document.getElementById("test").innerHTML = "replaced";

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download