How to Submit a Form with jQuery from an External Link
To submit a form using jQuery when a link outside of the form is clicked, you can use the submit() method of jQuery to trigger the form submission.
<-- The Form -->
<form id="myForm" action="/submit" method="POST">
<input type="text" name="username" placeholder="Enter username" />
<input type="password" name="password" placeholder="Enter password" />
</form>
<-- Link outside the form -->
<a href="#" id="submitLink">Submit Form</a>
You have a form (#myForm
) with input fields for username and password. There is also a link (#submitLink
) outside of the form.
$(document).ready(function() {
// When the link is clicked, submit the form
$('#submitLink').click(function(e) {
e.preventDefault(); //Prevent the default link behaviour
$('#myForm').submit(); //Submit the form
});
});
First when the link is clicked, the default action ( e.preventDefault()
) is prevented to avoid navigating to another page.
Then the $('#myForm').submit();
triggers the form submission.
This way clicking the link will submit the form just as if a submit button had been clicked inside the form.