How To Prevent Form Submit In Jquery

In this blog post, we will learn how to prevent a form from being submitted using jQuery. This is useful when you want to perform client-side validation or processing before allowing the form to be submitted to the server.

Step 1: Include the jQuery library

First, make sure to include the jQuery library in your HTML file. You can download it from the jQuery website or include it from a CDN (Content Delivery Network) like Google or Microsoft.

For this example, we will include the jQuery library from Google’s CDN:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

Step 2: Create the HTML form

Next, let’s create a simple HTML form with an input field and a submit button:

<form id="myForm">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name">
  <input type="submit" value="Submit">
</form>

Step 3: Add the jQuery script to prevent form submit

Now, we will add the jQuery script to prevent the form from being submitted when the submit button is clicked. We will use the submit() event handler and the preventDefault() method to achieve this.

Add the following script after including the jQuery library:

<script>
$(document).ready(function() {
  $('#myForm').submit(function(event) {
    event.preventDefault();
    alert('Form submission prevented.');
  });
});
</script>

Explanation of the jQuery script

  • The $(document).ready() function ensures that the script is executed after the DOM (Document Object Model) is fully loaded.
  • We then use $(‘#myForm’).submit() to bind the submit event to our form with the ID myForm.
  • The event.preventDefault() method is called inside the submit event handler to prevent the form from being submitted.
  • Finally, we display an alert to inform the user that the form submission has been prevented.

Now, when you click the submit button, the form will not be submitted, and you will see an alert message instead.

Conclusion

In this blog post, we have learned how to prevent a form from being submitted using jQuery. This technique can be useful when you want to perform client-side validation or processing before allowing the form to be submitted to the server.