skip to Main Content

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


  1. Passing the form ID as a parameter to the onSubmit function allows it to be reused across multiple forms.

    <form id="formName1">
      <!-- Your form content -->
      <button onclick="onSubmit('formName1')">Submit</button>
    </form>
    
    <form id="formName2">
      <!-- Your form content -->
      <button onclick="onSubmit('formName2')">Submit</button>
    </form>
    
    <script>
    function onSubmit(formId) {
      document.getElementById(formId).submit();
    }
    </script>
    

    Each form has a unique ID (formName1, formName2). The submit button’s onclick attribute calls the onSubmit function with the respective form ID as an argument.

    Login or Signup to reply.
  2. I am not sure that my answer fit your need.
    Maybe you can try something like this.

    function customSubmitFunction(formId){
      // do something
      //...
      //...
      // submit form
      document.getElementById(formId).submit();
    }
    
    // when page is loaded
    document.addEventListener('DOMContentLoaded', () => {
      // get all forms with css class managed-form
      document.querySelectorAll('.managed-form').forEach(form => {
        // add event listener to each form
        form.adeventListener('submit', e => {
          // prevent default form submission
          e.preventDefault();
          // get form id
          const formId = e.currentTarget.id;
          // call your your customer function
          customSubmitFunction(formId);
        });
      });
    });
    
    

    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)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search