complicatus complicatus - 1 month ago 6
HTML Question

Why does calling a JS function from onsubmit clear my form and console?

I am trying to call a JS function via the onsubmit event on a form. When I do this, my form input gets cleared (as does my JS console where I was trying to debug this issue). The JS from my functions appears to run, but I'm not sure why the form and console are cleared. Can someone explain?

If I call the same JS function via the onclick event on a button, the form and console are not cleared. Is there something special about calling this JS function based on the onsubmit event that causes the behavior I'm seeing?

Here is an HTML file that reproduces this issue:

<!DOCTYPE html>
<html lang="en">

<body>
<script>
function doThis(){
console.log("Hello World");
}
function doThat(){
console.log("Goodbye World");
}
</script>

<form onsubmit="doThis()">
<label>Address: </label><input type="text" name="address"><br>
<input type="submit" value="Submit"/>
</form>

<button onclick="doThat()">Submit Button</button>

</body>

</html>

Answer

Your form is getting submitted, which reloads the page and displays a new clean form and console.

To cancel submission add return false; to the onsubmit OR add a JavaScript breakpoint inside doThis().

Comments