Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

190
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda