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

189
Vistas
JavaScript get elements by class on submit iteration

I'm trying to iterate over forms for likes with flask and AJAX. It works if there is just a single form and I use get element by id. What am I doing wrong in JS while iterating over the class?

HTML:

<form class="like_form" method="POST">
    <input type="hidden" name="user_id" value="{{session['logged_in']['id']}}">
    <input type="hidden" name="like_id" value="32">
    <input type="submit" class="small_submit" value="🤍">
</form>

<form class="like_form" method="POST">
    <input type="hidden" name="user_id" value="{{session['logged_in']['id']}}">
    <input type="hidden" name="like_id" value="32">
    <input type="submit" class="small_submit" value="🤍">
</form>
var like_form = document.getElementsByClassName('like_form');
for(var i = 0; i < like_form.length; i++){
    like_form[i].onsubmit = function(e){
        e.preventDefault();
        console.log("clicked form")
        var form = new FormData(like_form)
        fetch("http://localhost:5000/test/form", { method :'POST', body : form})
            .then( response => response.json() )
            .then( data => {
                console.log(data)
                console.log(data['stars'])
                const stars = document.getElementById("stars")
                stars.innerHTML = `💜 ${data['stars']}` 
            })
    }
}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You need to get the form data of one form, not the collection of forms. To make it work I would suggest using a for..of loop, with let to get block scope:

for (let lform of like_form) {
    lform.onsubmit = function(e) {
        e.preventDefault();
        console.log("clicked form");
        var form = new FormData(lform); // <---

A second issue is document.getElementById("stars"). That element does not exist in your HTML. Moreover, if this is supposed to be an element that relates to the form (one for each form), then note that id attributes should be unique in HTML, so you should select such elements differently.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Ended up having to iterate through with the index :( Worked really well to change the like on the page too!! Just used the index for both the submit and changing the number on the page. See like_count[i].value

let like_form = document.getElementsByClassName('like_form');
let like_count = document.getElementsByClassName('like_count');
for(let i = 0; i < like_form.length; i++){
    like_form[i].onsubmit = function(e){
        e.preventDefault();
        console.log("clicked form")
        var form = new FormData(like_form[i])
        fetch("http://localhost:5000/test/form", { method :'POST', body : form})
            .then( response => response.json() )
            .then( data => {
                if (data['stars']){
                    console.log(data)
                    console.log(data['stars'])
                    const stars = document.getElementById("stars")
                    stars.innerHTML = `💜 ${data['stars']}` 
                    like_count[i].value = `💜 ${data['num']}`
                }
            })
        }
}
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