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

110
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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