jQuery submit form

Filed Under: jQuery

jQuery submit() function triggers when a user tries to submit a form. jQuery submit form method attaches a handler, which executes when the submit event is fired.

jQuery submit form

The syntax for submit form using jQuery submit() function:

  • submit()

This signature is used without any arguments. This method is a shortcut for .trigger( "submit" ).

  • submit(handler)

The handler is a function, which is executed when the form is submitted. This method is a shortcut for .on( "submit", handler ).

jQuery submit form example

Following example demonstrates submit() function usage for form submission using jQuery.


<!DOCTYPE html>
<html>
<head>
<title>jQuery Submit</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<style>
p {
margin: 0;
color: blue;
}
div,p {
margin-left: 10px;
}
.spanSuccess {
color: green;
}
</style>
</head>
<body>

<form action="javascript:alert( 'success!' );">
<div>
Name : <input type="text" name="Name" value="journalDev">
<input type="submit" value="Submit">
</div>
</form>
<span class="spanSuccess"></span>
<script>
$( "form" ).submit(function( event ) {

$( "span" ).text( "Submitted Successfully..." ).show();
event.preventDefault();

});
</script>
</body>
</html>

In above jQuery form submit example, you can see that the submit() method is triggered when you click on the Submit button. A text message is displayed as “Submitted Successfully…”.

jQuery form submit demo

You can try it yourself by submitting below form.

You may have noticed event.preventDefault() in the above code. You will see an alert, if you try the above example after removing this line. We used alert() method as the default action. So the event.preventDefault() is required in the code to prevent this default action.

That’s all for a quick jQuery form submit example. You can read learn jQuery by going through jQuery Tutorial.

Reference: API Doc

Comments

  1. Anand Paul says:

    Hi pankaj,

    I have a case, where I don’t want to submit the form on entering the enter key in a text box. I tried with preventDefault, but still it gets submitted. Fyi, I am using struts and jQuery.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages