My form has an ID:
<form id="formname">
I wish to use this as a variable in JavaScript.
function onSubmit(token) {
document.getElementById("Formname").submit();
}
I have to create a new script for every form with its specific ID in it.
Is there a way to give the script the ID to use as a variable?
like so?
const $id = FormId;
function onSubmit(token) {
document.getElementById($id).submit();
}
I´d searched the Internet and only find ways to do it the other way round – to change the ID from javascript.
2
Answers
Passing the form ID as a parameter to the onSubmit function allows it to be reused across multiple forms.
Each form has a unique
ID (formName1, formName2)
. The submit button’s onclick attribute calls theonSubmit
function with the respective formID
as an argument.I am not sure that my answer fit your need.
Maybe you can try something like this.
Don’t forget to add the css class
managed-form
on your forms.You will have to remove the "onsubmit" listener on button.
(This code is quite "naive" and can be improved)
(Out of scope, listening click on button to catch form submit event is often not a good solution because a form can also be submitted by pressing "Enter" key)