Skip to content
Advertisement

Stop form refreshing page on submit

How would I go about preventing the page from refreshing when pressing the send button without any data in the fields?

The validation is setup working fine, all fields go red but then the page is immediately refreshed. My knowledge of JS is relatively basic.

In particular I think the processForm() function at the bottom is ‘bad’.

HTML

JavaScript

JS

JavaScript

Advertisement

Answer

You can prevent the form from submitting with

JavaScript

Of course, in the function, you can check for empty fields, and if anything doesn’t look right, e.preventDefault() will stop the submit.

Without jQuery:

JavaScript
Advertisement