Home > database >  call function using onclick inside string for loop
call function using onclick inside string for loop

Time:02-04

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

CodePudding user response:

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})"

CodePudding user response:

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

  •  Tags:  
  • Related