Listen for form submission
This code will not work on snippets
(because snippets don't allow form submission), so I didn't create one, but it will in your site:
$(document).on('submit', 'form', function(e) {
e.preventDefault();
console.log('Form submitted');
});
$('body').append($('<form action=""><input type="submit" value="Submit dynamic form" /></form>'));
I used the
preventDefault
just to make sure the form will not get submitted. You can remove it in your code.
Here is a working jsfiddle:
https://jsfiddle.net/dekelb/gr94dg7q/
update - vanilla javascript solution:
document.addEventListener('submit', function(e) {
e.preventDefault();
console.log('Form submitted');
});
$('body').append($('<form action=""><input type="submit" value="Submit dynamic form" /></form>'));
Note the relevant javascript (no-jquery) is for the
submit
event, it's not related to the next line (regarding adding a new form to the document).
How do I get form submit event listener to work in js?
A form's submit event listener won't be triggered when you use the .submit()
method on the HTMLFormElement:
The submit event fires when the user clicks a submit button (
or<input type="submit">
) or presses Enter while editing a field (e.g.
<input type="text">
) in a form. The event is not sent to the form when
calling theform.submit()
method directly.- MDN
You can use the .requestSubmit()
method instead, which does trigger the onsubmit event handler of the form and performs constraint validation on the form:
/* vanilla js replacement */myForm = document.querySelector("form[name=myForm]")myForm.querySelector("button").addEventListener('click', function() { myForm.requestSubmit();})
myForm.addEventListener('submit', function(e) { e.preventDefault() console.log("Submitting form");})
<form name="myForm"> <input type="text" name="name" /> <button type="button">Click me</button></form>
Pure JS. How to add event listener for submit any form
You can query all forms and add event listener to each item:
document.querySelectorAll('form').forEach(form => form.addEventListener('submit', function(e){ e.preventDefault(); console.log('test');}, false));
<form> <button>submit</button></form>
Wy is my form submit event listener is not working
Your event is indeed firing, it just doesn't complete because of an error referencing the input
. Also, make sure that the script
is located just before the closing body
tag so that the HTML will be fully parsed by the time the script
is encountered.
Replace const form = document.forms['testRegForm']
with const form = document.querySelector("form")
and modify your reference to the input
as with a valid selector as shown below.
<!doctype html>
<html>
<head>
<title>test</title>
</head>
<body>
<form name="testRegForm" style="font-family: Aladin;" >
<p>Register using mobile Number: </p>
<input type="number" placeholder="Number" pattern="\d{3}[\-]\d{3}[\-]\d{4}" name="mobile" maxlength="10" required><br><br>
<button type="submit">Submit</button>
<p></p>
</form>
<script>
// A standard API for locating a DOM element is .querySelector()
// which takes any valid CSS selector:
const form = document.querySelector("form");
// Get your DOM references that you'll work with more than once
// only once, so this has been moved outside of the event callback.
// Also, "mobile" isn't an attribute, so your selector wasn't working
// for it. And, it's best to get references to DOM elements, rather
// than a particular property of an element so that if you decide you
// want a difference property value, you've already got the element
// reference and won't need to scan for it again.
var x = document.querySelector("[required][name='mobile']");
form.addEventListener('submit', e => {
e.preventDefault();
alert("Test");
if (x.value == "") {
alert("Mobile Number is required");
return false;
}else {
alert(x.value);
fetch(scriptURL, { method: 'POST', body: new FormData(form)})
.then(response =>
alert('Your request is submitted. We will get in touch with you soon')
).catch(error => alert(error.message))
}
});
</script>
<body>
</html>
Listen to submit event with two form on same page
Ok found the issue, my bad, the two forms had the same ID, and that's why my event wasn't catch by this function.
Listening to all form submit events, including dynamically added forms
Yes, you can use jQuery for this
$(document).on("submit", "form", function(e){
//your code
})
Why won't form.submit() trigger the submit event?
According to MDN:
The form's onsubmit event handler (for example,
onsubmit="return false;"
) will not be triggered when invoking this method from Gecko-based applications. In general, it is not guaranteed to be invoked by HTML user agents.
To get around this issue, try using dispatchEvent()
:
var form = document.querySelector('form');
form.addEventListener('submit', function () { console.log('invoked'); return false;});
// form.submit();form.dispatchEvent(new Event('submit'));
<form></form>
Related Topics
How to Update State.Item[1] in State Using Setstate
Switch Statement for Greater-Than/Less-Than
How to Tell If Caps Lock Is on Using JavaScript
Memory Leak Risk in JavaScript Closures
Why Do Results Vary Based on Curly Brace Placement
Using Jquery How to Get Click Coordinates on the Target Element
How to Maintain a Websockets Connection Between Pages
JavaScript Get X and Y Coordinates on Mouse Click
Capture Frames from Video with HTML5 and JavaScript
Sort an HTML List with JavaScript
Is It Safe to Store a Jwt in Localstorage with Reactjs
Difference Between Knockout View Models Declared as Object Literals VS Functions
How to Implement Authenticated Routes in React Router 4
How to Update an "Array of Objects" with Firestore
How to Make a Simple Image Upload Using JavaScript/Html