JavaScript Submit
The submit()
method is used to submit a form programmatically using JavaScript and triggers the form submission process. In this page, we will discuss the syntax, example, output, explanation, use, important points, and summary of the submit()
method in JavaScript.
Syntax
formObject.submit();
Example
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Submit Example</title>
</head>
<body>
<form id="myForm" action="submit.php" method="post">
<input type="text" name="username" placeholder="Enter your username" /><br />
<input type="password" name="password" placeholder="Enter your password"><br>
<button type="button" onclick="submitForm()">Submit</button>
</form>
<script>
function submitForm(){
document.getElementById('myForm').submit();
}
</script>
</body>
</html>
Output
When you click on the "Submit" button, the submitForm()
function is called which submits the form with the id="myForm"
using the submit()
method. The form will be directed to the URL specified in the action
attribute of the form element, in this case "submit.php".
Explanation
The submit()
method can be used to submit a form using JavaScript. This method can be used to submit a form without the need for the user to click a submit button. We just need to call the method on the form element using JavaScript.
In the above example, a form is created with the id="myForm"
. When the Submit button is clicked, the submitForm()
function is called which gets the reference to the form element using document.getElementById
and submit the form with the submit()
method.
Use
The submit()
method can be used to submit the form when:
- The user clicks a button (alternative to clicking a submit button).
- When the form is validated using JavaScript and the data is correct.
- In an AJAX request which sends/retrieves form data using JavaScript.
Important Points
- The
submit()
method can only be called on a form element. - The
submit()
method triggers the form submission process. - If the form's
action
attribute is not set, the form will submit to the current page URL. - If the
method
attribute is not specified, the method defaults toGET
. - The
submit()
method submits the form with all the form element values. - It will also submit the form even if it doesn't contain any data.
Summary
The submit()
method submits a form programmatically using JavaScript without the need for user interaction. It is a quick and efficient way to submit a form using JavaScript.