Skip to content
Advertisement

Generalization of JQuery submit function

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:

$('#form-name').submit(function(event) {
    event.preventDefault();
    const formData = new FormData($('#form-name')[0]);
    const json = JSON.stringify(Object.fromEntries(formData));
    ws.send(json);
});

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:

function custom_submit(form, event) {
    event.preventDefault();
    const formData = new FormData($(form)[0]);
    const json = JSON.stringify(Object.fromEntries(formData));
    ws.send(json);
}

and then use:

$('#form-name').submit(custom_submit('#form-name`, event));

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:

form-ws-*

Advertisement

Answer

$('form').on('submit', function(event) {
    event.preventDefault();
    const formData = new FormData(this);
    const json = JSON.stringify(Object.fromEntries(formData));
    ws.send(json);
}); 

will handle all forms on the page

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement