I have been having problems lately with a page reloading during form submission. I finally found out that the page reloads when I submit the form with EventListener, but it doesn't reload with onclick form submission. The code below is how I tested that. Can someone please explain to me why?
<html>
<head>
<title>Reload Page Test</title>
<script>
document.addEventListener("DOMContentLoaded", function () {
document.querySelector("#asubmit").addEventListener("click", test);
document.querySelector("#bsubmit").onclick = test;
function test(){
const name = document.getElementById("name").value;
const age = document.getElementById("num").value;
document.getElementById(
"result"
).innerHTML = `${name} is ${age}years old.`;
return false;
};
});
</script>
</head>
<body>
<div>
<form>
<input type="text" id="name" />
<input type="number" id="num" />
<input type="submit" id="asubmit" value="Event Listener Submit"/>
<input type="submit" id="bsubmit" value="On Click Submit">
</form>`enter code here`
</div>
<div id="result"></div>
</body>
</html>
CodePudding user response:
Returning false from an onclick function will prevent the default behaviour.
The return value of an event listener callback is meaningless.
Use event.preventDefault()
instead.
function test(event) {
// ...
event.preventDefault();
}