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

109
Visualizações
call function using onclick inside string for loop

I am creating a table depending on the result of a function for then append in a div like this:

    let result = document.getElementById("result");
    consultCities();
    
    function consultCities (){
        consultarAPI(username, password, "cities")
        .then((response) => {
            if(response.login !== "Fail"){
                let table = "";
                let thead = "";
                let tbody = "";
    
                thead += `<tr>
                            <th>Citie</th>
                            <th>Dane</th>
                            <th>Look Institution</th>
                          </tr>`
                for(let i = 0; i < response.data.length;  i += 1 ){
    
                    tbody += `<tr>
                                    <td>${response.data[i].name}</td>
                                    <td>${response.data[i].dane}</td>
                                    <td><button type="button" id="ver" onclick="${consultInstitutions(response.data[i].dane)}">Ver</button></td>
                               </tr>`
                }
    
                table += `<table class="table table-bordered">
                            <thead>
                                ${thead}
                            </thead>
                            <tbody>
                                ${tbody}
                            </tbody>
                          </table>`
    
                result.innerHTML = table;
            }else{
                alert("El Usuario no existe o la opción no existe");
            }
        });
    }

function consultInstitutions(codCity){
    console.log(codCity);
}

The problem is the onclick trigger runs automatically although I don't click in any button, my question is there a best way that I can set onclick a button for a string?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I think the issue here is that you are running the function immediately by placing it within ${}. Instead you just want to place the variable within the ${}.

onclick="consultInstitutions(${response.data[i].dane})"
about 4 years ago · Juan Pablo Isaza Relatório

0

Here is an alternative version of your script. I took the liberty of inventing some test data in order to make it an MCVE.

const D={login:"OK",data:[
 {name:"Rome",dane:"Gio"}, {name:"Kiev",dane:"Ivan"}, {name:"Paris",dane:"Lorraine"}, {name:"Ohio",dane:"Matt"}, {name:"Minsk",dane:"Sergey"}]},
  tbl = document.getElementById("result");
tbl.innerHTML=makeTable(D);
tbl.onclick=ev=>{
 if(ev.target.tagName==="BUTTON")
  console.log(ev.target.closest("td").previousElementSibling.textContent)
}

function makeTable(resp){
  if(resp.login !== "Fail")
  return `<table class="table table-bordered"><thead><tr><th>Citie</th><th>Dane</th><th>Look Institution</th></tr></thead><tbody>`
 + resp.data.map(r=>
  `<tr><td>${r.name}</td><td>${r.dane}</td><td><button type="button">Ver</button></td></tr>`).join("\n")
 + "</tbody></table>";
else
  alert("El Usuario no existe o la opción no existe");
}
<div id="result"></div>

I used a delegated attachment handling: The click event is listened to by the <table> element but the action only happens if the clicked element (ev.target) happens to be a "BUTTON". In that case the function looks for the text content of the previous <TD> element and cinsole.log()s it. Doing it this way I can keep the HTML-template strings in my markup generator function makeTable() very simple.

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