Core JavaScript

Prevent a Button Page Refresh

This JavaScript program shows how to prevent a page refresh when a button is inside a form element. The key is to add the type="button" specifier. Here, we can see the difference when the buttons are pressed. The first button refreshes the page so that the message only appears briefly and is erased when the page is refreshed. The second button prevents the page refresh and retains the message inside the paragraph element.

PreventButtonRefresh.html

<!DOCTYPE html>
<html>
	<head>
		<title>XoaX.net's Javascript</title>
		<script type="text/javascript" src="PreventButtonRefresh.js"></script>
	</head>
	<body>
		<form>
			<button  onclick="FillElement()">Refresh Page</button>
			<button type="button" onclick="FillElement()">No Refresh</button>
		</form>
		<p id="idFill"></p>
	</body>
</html>

PreventButtonRefresh.js

function FillElement(qEvent) {
	document.getElementById("idFill").innerHTML = "This was filled.";
}
 

Output

 
 

© 2007–2025 XoaX.net LLC. All rights reserved.