complicatus complicatus - 1 year ago 121
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">

function doThis(){
console.log("Hello World");
function doThat(){
console.log("Goodbye World");

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

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



Answer Source

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().

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