How To Reset Form In Jquery

In this blog post, we will learn how to reset a form using jQuery. Resetting a form is useful when you want to clear all the input fields inside a form, resetting them to their default values. This can be particularly helpful after a form has been submitted, or when you want the user to start over with a clean slate.

Resetting a Form Using the native HTML reset button

Before we dive into jQuery, it’s worth mentioning that HTML provides a native way to reset a form. You can add a reset type button inside the form, like so:

<form>
    ...
    <input type="reset" value="Reset">
</form>

However, this approach has some limitations. For example, it may not clear custom input elements or undo changes made by JavaScript. Additionally, it does not provide the flexibility and control that jQuery offers.

Using jQuery to Reset a Form

Now, let’s see how we can reset a form using jQuery. To do this, we’ll take advantage of the .trigger() method, which allows us to trigger an event on a specified element. In this case, we’ll trigger the reset event on our form.

Here’s an example:

$("#myForm").trigger("reset");

In this example, we’re targeting a form with the ID myForm and triggering the reset event. This will reset all of the form’s input fields to their default values.

Resetting a Form with a Button Click

Now, let’s say we want to reset the form when the user clicks a button. We can do this by binding the click event to our button and executing the above code inside the event handler. Here’s an example:

$("#resetButton").click(function() {
    $("#myForm").trigger("reset");
});

In this example, we’re targeting a button with the ID resetButton, and when it’s clicked, we’re triggering the reset event on our form.

Resetting a Form after Submission

We can also reset a form automatically after it has been submitted. To do this, we’ll use jQuery’s .submit() method to bind an event handler to the form’s submission event. Inside the event handler, we’ll use the .trigger() method to reset the form:

$("#myForm").submit(function(e) {
    e.preventDefault();
    ... // process the form data
    $(this).trigger("reset");
});

In this example, we’re preventing the default form submission action using e.preventDefault(), processing the form data, and then resetting the form.

Conclusion

Resetting a form using jQuery is a simple and effective way to clear all input fields inside the form, allowing users to start with a clean slate. With just a few lines of code, you can easily reset a form after submission or when the user clicks a button. Happy coding!