How to Submit Form on Click in JavaScript
-
Submit a Form by Clicking a Link and Using the
submit()
Function in JavaScript -
Submit a Form by Clicking a Button and Using the
submit()
Function in JavaScript
This tutorial will discuss how to submit a form using the submit()
function in JavaScript.
Submit a Form by Clicking a Link and Using the submit()
Function in JavaScript
In JavaScript, you can create a form using the form
tag, you can give the form an id using the id
attribute, and after that, you have to choose a method to submit your form like, you can submit the form when a link or a button is clicked. Now, there are two methods to submit a form, and you can either do it inside the HTML code by using the onclick
attribute or do it inside the JavaScript. For example, let’s submit a form inside the HTML using the onclick
attribute. See the code below.
<form id="FormId">
<a href="FormLink" id = "LinkID" onclick="document.getElementById('FormId').submit();"> SubmitForm </a>
</form>
You can change the form
id and the link id in the above code according to your requirements. This method is not recommended because you are mixing HTML with JavaScript code. You can also do that separately in JavaScript by using the id of both form and link. For example, let’s do the above operation using separate JavaScript. See the code below.
var myform = document.getElementById('FormId');
document.getElementById('LinkId').addEventListener('click', function() {
myform.submit();
});
This method is recommended because the HTML and JavaScript are in separate files. Note that you have to use the form id and link id that you have defined in the HTML to get those elements in JavaScript. The form will be submitted when the link is clicked.
Submit a Form by Clicking a Button and Using the submit()
Function in JavaScript
You can use a button to submit a form. There are two methods to submit a form, and you can either do it inside the HTML code by using the onclick
attribute or do it inside the JavaScript. For example, let’s submit a form inside the HTML using the onclick
attribute. See the code below.
<form id="FormId">
<button id = "ButtonId" onclick="document.getElementById('FormId').submit();"> SubmitForm </button>
</form>
Similar to the above method, this method is not recommended because you are mixing HTML with JavaScript code. Let’s do the above operation using separate JavaScript.
var myform = document.getElementById('FormId');
document.getElementById('ButtonId').addEventListener('click', function() {
myform.submit();
});