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

132
Visualizações
modify function input through for loop javascript

I have a series of buttons with some names on them; when a button is clicked the name on it is added in a list. This last operation is done by a function which takes as input the id of the button. When I write all that stuff explicitly all works fine:

<!DOCTYPE html>
<html>
<head>
    <script>
        inventory=[]

        function addinv(variable) {
            item=document.getElementById(variable).innerHTML
            if (item!='Ok') {
                if (inventory.length<2){
                    inventory.push(item)
                    document.getElementById(variable).innerHTML='Ok'
                }
            }

        }

        function location0() {
            document.getElementById("1").innerHTML="Spada"
            document.getElementById("1").setAttribute('onclick','addinv(1)')
            document.getElementById("2").innerHTML="Corda"
            document.getElementById("2").setAttribute('onclick','addinv(2)')
            document.getElementById("3").innerHTML="Acciarino"
            document.getElementById("3").setAttribute('onclick','addinv(3)')
        }

    </script>
</head>
<body>
    <button type="button" id="1" onclick=""></button>
    <button type="button" id="2" onclick=""></button>
    <button type="button" id="3" onclick=""></button>
    <script>location0()</script>


</body>
</html>

I would like to use a for loop in order to set the names on the buttons and calling the addinv function. For that I changed the function location0 as follows:

function location0() {
    equip=["Spada", "Corda", "Acciarino"]
        for (i=1; i<4; i++) {
            document.getElementById(i).innerHTML=equip[i-1]
            document.getElementById(i).setAttribute('onclick','addinv(i)')
        }
    }

Now buttons still have the right name on them, but the addinv function does not work properly: it seems to me that all buttons calls addinv(4)

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

0

Try to replace the for-loop as below:

for (let i=1; i<4; i++) {
   document.getElementById(i).innerHTML=equip[i-1]
   document.getElementById(i).addEventListener("click",()=>{addinv(i)});
}

I attached a sample code for your reference.

about 4 years ago · Juan Pablo Isaza Relatório

0

Instead of passing the id to addinv(), I'd suggest passing a ref to the item. So I slightly modified location0() and the call to addinv().

function location0() {
    const equip=["Spada", "Corda", "Acciarino"]
    
        for (let i=0; i<equip.length; i++) {
          let item = document.getElementById(i+1)
          item.innerHTML = equip[i];
          item.setAttribute('onclick', 'addinv(this)')
        }
    }

Then change addinv() to this. This should work.

function addinv(item) {
    let text = item.innerHTML;
    if (text != 'Ok') {
        if (inventory.length < 3) {
            inventory.push(text)
            item.innerHTML = 'Ok'
        }
    }


}
about 4 years ago · Juan Pablo Isaza Relatório

0

<!DOCTYPE html>
<html>
<head>
    <script>
        inventory=[]

        function addinv(variable) {
            item=document.getElementById(variable).innerHTML
            if (item!='Ok') {
                if (inventory.length<3){
                    inventory.push(item)
                    document.getElementById(variable).innerHTML='Ok'
                }
            }

        }

        function location0() {
            document.getElementById("1").innerHTML="Spada"
            document.getElementById("1").setAttribute('onclick','addinv(1)')
            document.getElementById("2").innerHTML="Corda"
            document.getElementById("2").setAttribute('onclick','addinv(2)')
            document.getElementById("3").innerHTML="Acciarino"
            document.getElementById("3").setAttribute('onclick','addinv(3)')
            
        }

    </script>
</head>
<body>
    <button type="button" id="1" onclick=""></button>
    <button type="button" id="2" onclick=""></button>
    <button type="button" id="3" onclick=""></button>
    <script>location0()
    
    </script>
</body>

</html>

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