In my web application I have dozen of forms, of course each one with a different id
. Then in my JavaScript file I wrote a custom handler for the submit
event:
JavaScript
x
7
1
$('#form-name').submit(function(event) {
2
event.preventDefault();
3
const formData = new FormData($('#form-name')[0]);
4
const json = JSON.stringify(Object.fromEntries(formData));
5
ws.send(json);
6
});
7
I want to avoid to write the above code for each form. As first step I can just wrap it in another function, something like this:
JavaScript
1
7
1
function custom_submit(form, event) {
2
event.preventDefault();
3
const formData = new FormData($(form)[0]);
4
const json = JSON.stringify(Object.fromEntries(formData));
5
ws.send(json);
6
}
7
and then use:
JavaScript
1
2
1
$('#form-name').submit(custom_submit('#form-name`, event));
2
but this is not a valid syntax. In any case I still need to “connect” each form to the custom function, writing two times its name.
Is there a way to match all the forms that have a specific prefix and connect all of them to my custom submit function passing both the form id
and the event
variable as above? Example of prefix:
JavaScript
1
2
1
form-ws-*
2
Advertisement
Answer
JavaScript
1
7
1
$('form').on('submit', function(event) {
2
event.preventDefault();
3
const formData = new FormData(this);
4
const json = JSON.stringify(Object.fromEntries(formData));
5
ws.send(json);
6
});
7
will handle all forms on the page