querySelectorAll() for all forms with addEventListener for different forms

queryselectorall addeventlistener
queryselectorall multiple classes
queryselectorall onclick
queryselectorall foreach
javascript foreach
queryselectorall jquery
addeventlistener multiple elements
getelementbyid

Hello ladies and gentleman.

Currently I am trying to create a event listener to all forms that I have in my website, but... (I'm a backend developer so frontend it's nightmare for me) so now I'm trying to work with JavaScript (pure Vanilla JS) without any framework or nothing... and I use ES5.

So what I want to do is to send the name of the differents <form> that we have but I'm struggling so hard with this one because I am using the querySelector('form') and I JUST figured that it is not correct because it will only select one <form> so the correct way must use this querySelectorAll('form') BUT there's another problem by "standard" of my company we not define the name of the forms, so we "define" our forms with action='/searchExample currently we have about 32 nameless <form> and we only have two forms with name login_form and registration (only for those we defined the name)

   function formSubmitTrack() {
    var formName = '';
    var form = document.querySelector('form');

    form.addEventListener('submit', function() {
      formName = form.getAttribute('action')
        ? form.getAttribute('action')
        : form.getAttribute('name');

      var data = {
        event: 'e_formSubmit',
        formName: formName
      };

      send(data);
    });

I will be very grateful if someone can help me to this particular case because I don't want to create 32 function form1...32() for per <form> this code for example will apply for one form:

So I was trying to this one: (step 1 to capture the values)

function formSubmitTrackAll() {
      var form = document.querySelectorAll('form');

      for (let i = 0; i < form.length; i++) {
          const element = form[i];
          var formName = element.name;
          var formAction = element.getAttribute('action');

          console.log(formName);
          console.log(formAction);

          if(formName === ""){
              var data = {
                  event: 'e_forSubmit',
                  formName: formAction,
              }
          } else {
            var data = {
                  event: 'e_forSubmit',
                  formName: formName,
              }
          }

          send(data);
      }
  }

so step 2, is to trigger the eventListener('click') for when the user clicks the form, this is my code but I'm confused whit this part for the eventListener:

function formSubmitTrackAll() {
      var form = document.querySelectorAll('form');

      for (let i = 0; i < form.length; i++) {
          const element = form[i];
          var formName = element.name;
          var formAction = element.getAttribute('action');

          console.log(formName);
          console.log(formAction);

          if(formName === ""){
              formName.addEventListener('click', function() {
                var data = {
                    event: 'e_forSubmit',
                    formName: formAction,
                }
              })

          } else {
            formAction.addEventListener('click', function() {
                var data = {
                    event: 'e_forSubmit',
                    formName: formAction,
                }
              })
          }

          send(data);
      }
  }

and I use this HTML code to test

<form action="something">
    <input type="email"></input> 
    <button class="btn btn-safe col-xs-6"></button>
</form>
<br><br>

<form name='registration'>
    <button class="btn btn-security col-xs-6"></button>
</form>

Thank you for your patience.

I am not sure what you are asking.

function formSubmitTrackAll() {
      var form = document.querySelectorAll('form');

      for (let i = 0; i < form.length; i++) {
          const element = form[i];
          var formName = element.name;
        

          console.log(formName);
       

          if(formName === ""){
              form[i].addEventListener('click', function() {
                var formAction = element.getAttribute('action');
                var data = {
                    event: 'e_forSubmit',
                    formName: formAction,
                }
                console.log(data);
              });

          } else {
            form[i].addEventListener('click', function() {
               var formAction = element.getAttribute('name');
                var data = {
                    event: 'e_forSubmit',
                    formName: formAction,
                }
                  console.log(data);
              });
          }

          //send(data);
      }
  }
  formSubmitTrackAll();
<form action="something">
    <input type="email"></input> 
    <button class="btn btn-safe col-xs-6"></button>
</form>
<br><br>

<form name='registration'>
    <button class="btn btn-security col-xs-6"></button>
</form>

How to add an event listener to multiple elements in JavaScript, In JavaScript you add an event listener to a single element using this syntax: document. You can do this in 2 ways. You can call querySelectorAll() on all elements with a specific class, then use forEach() to iterate on them:. Definition and Usage. The querySelectorAll() method returns a collection of an element's child elements that match a specified CSS selector(s), as a static NodeList object. The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers.

You need your send(data) call to be inside of the click event handlers, not outside. As it currently stands, you're calling send(data) while looping through the forms instead.

Document.querySelectorAll(), The Document method querySelectorAll() returns a static (not live) NodeList Multiple selectors may be specified by separating them using commas. To obtain a NodeList of all of the <p> elements in the document: fgColor · firstElementChild · forms · fullscreen · fullscreenEnabled · head · height  The querySelectorAll() method returns all elements in the document that matches a specified CSS selector(s), as a static NodeList object. The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers.

I do not know if I interpret your question correctly but I understand that you require that when sending a form, prior to being sent, obtain the event and name based on the conditions you mention. I assume that the form will be sent using POST so you can:

  1. Get the data
  2. Create hidden type inputs and assign them the corresponding data values
  3. Attach these inputs to the form
  4. Send the form

Please consider this example

Having this set of forms

<form name="login_form"><button type="submit">Send</button></form>
<form name="registration"><button type="submit">Send</button></form>
<form action="action_name1"><button type="submit">Send</button></form>
<form action="action_name2"><button type="submit">Send</button></form>
<form action="action_name3"><button type="submit">Send</button></form>
<form action="action_name4"><button type="submit">Send</button></form>
<form action="action_name5"><button type="submit">Send</button></form>

Given this logic

var forms = document.querySelectorAll('form');

function handleforms(forms) {
    for (var i = 0; i < forms.length; i++) {
        var data = { event: 'e_formSubmit' };
        var form = forms[i];

        data.name = form.hasAttribute('name') ? form.getAttribute('name') : form.getAttribute('action');

        form.addEventListener('click', function(event) {
            event.preventDefault();

            var eventInput = document.createElement('input');
            var nameInput = document.createElement('input');

            eventInput.setAttribute('type', 'hidden');
            eventInput.setAttribute('name', 'event');
            eventInput.setAttribute('value', data.event);

            nameInput.setAttribute('type', 'hidden');
            nameInput.setAttribute('name', 'name');
            nameInput.setAttribute('value', data.name);

            form.appendChild(eventInput);
            form.appendChild(nameInput);

            form.submit(); // In processing action ypu will have access to event and name 
        })
    }
}

handleforms(forms);

I hope it is useful for you

Forms and Form Fields :: Eloquent JavaScript, A web form consists of any number of input fields grouped in a <form> tag. HTML The JavaScript interface for such elements differs with the type of the element. We'll go querySelector("form"); console.log(form.elements[1].type); // → password addEventListener("change", function() { document.body.style.​background  Document.querySelectorAll() Jump to: The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors. Note: This method is implemented based on the ParentNode mixin's querySelectorAll() method.

Loop Over querySelectorAll Matches, Not all browsers support forEach on NodeLists, but for those that do: then would give you access to other array methods while you're at it. The addEventListener() method attaches an event handler to the specified element. Tip: Use the removeEventListener() method to remove an event handler that has been attached with the addEventListener() method. Tip: Use the document.addEventListener() method to attach an event handler to the document.

The Basics of DOM Manipulation in Vanilla JavaScript (No jQuery , Whenever we need to perform DOM manipulation, we're all quick to querySelector() method, which takes an arbitrary CSS selector as an argument: addEventListener() method to add as many events of as many types as  The Element method querySelectorAll () returns a static (not live) NodeList representing a list of elements matching the specified group of selectors which are descendants of the element on which the method was called. Note: This method is implemented based on the ParentNode mixin's querySelectorAll () method.

HTML DOM querySelectorAll() Method, accessKey addEventListener() appendChild() attributes blur() The querySelectorAll() method returns all elements in the document that matches a These are used to select HTML elements based on their id, classes, types, attributes, values of attributes, etc. For multiple selectors, separate each selector with a comma. We’ve written an updated article about this: A Bunch of Options for Looping Over querySelectorAll NodeLists. Not all browsers support forEach on NodeLists, but for those that do: buttons.forEach((button) => { button.addEventListener('click', => { console.log("forEach worked"); }); });

Comments