 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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>Advertisements
 