Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$('#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-*

>Solution :

$('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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading