How to prevent form from being submitted?



We can easily prevent forms on a web page to submit using the event.preventDefault() or returning Flase on submit event handler. Let us see the example one by one −

Prevent form from being submitted using the event.preventDefault()

To prevent form from being submitted, use the event.preventDefault() i.e. −

<form onsubmit="event.preventDefault();">

Example

Let us see the complete example −

<!DOCTYPE html>
<html>
<body> 
   <h1>Details</h1>
   <form onsubmit="event.preventDefault();">
      <p>Select the subject you want to choose:</p>
      <div>
         <input type="radio" id="prog" name="subject" value="prog">
         <label for="prog">Programming</label>
         <input type="radio" id="dev" name="subject" value="dev">
         <label for="dev">Web Development</label>        
         <input type="radio" id="db" name="subject" value="db">
         <label for="db">Database</label>
      </div><br/>
      <div>
         <button id="submit" type="submit">Submit</button>
      </div>
      </form>
</body>
</html>

Output

Select any option and click Submit. The form won’t submit −

Prevent form from being submitted using the return false on submit event handler

To prevent form from being submitted, use the return false on submit event handler −

<form onsubmit="return false;">

Example

Let us see the complete example −

<!DOCTYPE html>
<html>
<body> 
   <h1>Details</h1>
   <form onsubmit="return false;">
      <p>Select the subject you want to choose:</p>
      <div>
         <input type="radio" id="prog" name="subject" value="prog">
         <label for="prog">Programming</label>
         <input type="radio" id="dev" name="subject" value="dev">
         <label for="dev">Web Development</label>
         <input type="radio" id="db" name="subject" value="db">
         <label for="db">Database</label>
      </div><br/>
      <div>
         <button id="submit" type="submit">Submit</button>
      </div>
   </form>
</body>
</html>

Output

Select any option and click Submit. The form won’t submit −


Advertisements