Stop making form to reload a page in JavaScript


Let’s say what we need to achieve is when the user submits this HTML form, we handle the submit event on client side and prevent the browser to reload as soon as the form is submitted

HTML form

<form name="formcontact1" action="#">
<input
type='text'
name='email'
size="36"
placeholder="Your e-mail :)"/>
<input
   type="submit"
   name="submit"
   value="SUBMIT"
   onclick="ValidateEmail(document.formcontact1.email)"
/>
</form>

Now, the easiest and the most reliable way of doing so is by tweaking our ValidateEmail() function to include the following line right at the top of its definition −

function ValidateEmail(event, inputText){
   event.preventDefault();
   //remaining function logic goes here
}

What preventDefault() does is that it tells the browser to prevent its default behaviour and let us handle the form submitting event on the client side itself.

The full HTML code for this is −

Example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form name="formcontact1" action="#">
<input
type='text'
name='email'
size="36"
placeholder="Your e-mail :)"/>
<input
   type="submit"
   name="submit"
   value="SUBMIT"
   onclick="ValidateEmail(document.formcontact1.email)"
/>
</form>
<script>
{
   function ValidateEmail(event, inputText){
      event.preventDefault();
      //remaining function logic goes here
   }
}
</script>
</body>
</html>

Updated on: 18-Aug-2020

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements