To handle form submission events with jQuery, you can use the submit()
function. Here is an example of how you can do this:
<form id="myForm">
<input type="text" id="name" name="name" placeholder="Enter your name" required/>
<button type="submit">Submit</button>
</form>
<script>
tag in your HTML file.$(document).ready(function() {
// Handle form submission event
$("#myForm").submit(function(event) {
// Prevent default form submission action
event.preventDefault();
// Get the form data
var formData = $(this).serializeArray();
console.log(formData);
// You can perform further operations with the form data here, like sending it to a server using ajax
// Reset the form
$(this).trigger("reset");
});
});
In the above code, we attach an event handler to the form with the ID myForm
. When the form is submitted, the submit()
function is called, passing an anonymous function as the event handler.
Inside the event handler, we prevent the default form submission action using event.preventDefault()
. This prevents the page from refreshing.
We then use $(this).serializeArray()
to get the form data as an array of objects, where each object has name
and value
properties. We log this data to the console for demonstration purposes.
You can perform further operations with the form data, such as sending it to a server using Ajax.
Finally, we reset the form by triggering the reset
event on it using $(this).trigger("reset")
.