Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

169
Vistas
How to target a specific form on submit if multiple forms are present with same class name in one page using vanilla javascript?

I'm interested in one vanilla JS function that will target the specific form that was submitted while having multiple forms with the same class name on the same page. Using IDs is not an option for each form.

Let's say I have 10 forms like the following on some page:

<form class="add_to_cart">
    <div class="btn btn__add_to_cart">Add To Cart</div>
    <input type="hidden" id="some_product_id">
</form>

How can I grab with JS (no jQuery please) the specific form on which the div element was clicked (I didn't use button element on purpose, i'm interested in the div option)?

Will really appreciate your help.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

The real problem is that you are doing this in a more difficult way than it needs to be

If you just do:

<form class="add_to_cart">
    <input type='submit' class="btn btn__add_to_cart" value='Add To Cart' />
    <input type="hidden" id="some_product_id">
</form>

Clicking the button will submit the correct form. You can restyle the button using CSS if you wish

BUT...

If you the divs are necessary, you can do something like

document.querySelectorAll("DIV").forEach(function(elem) {
  elem.addEventListener("click", function(e) {
    e.target.closest("form").submit();
  });
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

Not sure what you want to do with it but here is a click handler using the classes btn and btn__add_to_cart that are a div.

I also added a form submit handler for the closest form that was clicked.

let submitEvent = new CustomEvent("submit", {
  "bubbles": true,
  "cancelable": true
});

function logSubmit(event) {
  console.log(`Form Submitted! Time stamp: ${event.timeStamp}`);
  let button = event.currentTarget.querySelectorAll('input')[0];
  console.log(`Form button ID: ${button.id}`);
  event.preventDefault();
}
var evt = new CustomEvent("submit", {
  "bubbles": true,
  "cancelable": true
});
let allforms = document.querySelectorAll('form.add_to_cart');
Array.from(allforms).forEach(function(element) {
  element.addEventListener('submit', logSubmit);
});

function clickedMe(event) {
  console.log(event.currentTarget === this) // logs `true`
  let closestForm = event.currentTarget.closest('form.add_to_cart');
  console.log("My Classes:", this.className);
  closestForm.dispatchEvent(submitEvent);
}
const clickableButtons = document.querySelectorAll(`div.btn.btn__add_to_cart`);
console.log(clickableButtons.length);
Array.from(clickableButtons).forEach(function(element) {
  element.addEventListener('click', clickedMe, false);
});
<form class="add_to_cart">
  <div class="btn btn__add_to_cart">Add To Cart</div>
  <input type="hidden" id="some_product_id">
</form>
<form class="add_to_cart">
  <div class="btn btn__add_to_cart">Add To Cart 2</div>
  <input type="hidden" id="some_product_id2">
</form>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda