The submit
event occurs when the form is submitted. Like when you click submit button or you press Enter on an input type="text"
element.
The method submit
is used to submit the form manually.
When the submit
event occurs, at the end of the event, the browser submits the form to the server. It is default action. You can prevent this default action using event.preventDefault()
and stop sending the form to the server. You can also use return false;
to prevent submitting to the server.
Note that the event occurs on form
element. Not on the button or any input element.
To submit a form to the server manually, we can call form.submit()
.
Then the submit
event is not generated. It is assumed that if the programmer calls form.submit()
, then the script already did all related processing.
let form = document.createElement('form'); form.action = 'https://google.com/search'; form.method = 'GET'; form.innerHTML = '<input name="q" value="test">'; // the form must be in the document to submit it document.body.append(form); form.submit();
<div class="box"> <form id="myForm" onsubmit="return false;"> <input type="test" name="name"> <button type="submit" id="formSubmit">Submit</button> </form> <script type="text/javascript"> formSubmit.onclick = function(){ alert("Manually Submitting !"); myForm.submit(); }; </script>