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

261
Visualizações
How to display each buttons in one function in JavaScript

So, I'm trying to build a calculator and the first thing I want to do is to display all the buttons in my output. I have created a function called displayButtons and inside, I got the first 2 buttons by id however, when I try to display them, only the number 2 displays. One way to fix this is to create a function for each numbers and then it'll work but that's not what I want. I've also tried nesting the functions for each number within a function, but I wasn't able to call it properly onclick. Any ideas? Thanks in advance!

HTML code:

<div id="output"></div>
        <div class="numbers">
            <button value="1" id="one" onclick="displayButtons()">1</button>
            <button value="2" id="two" onclick="displayButtons()">2</button>

JS code:

function displayButtons() {

    var one = document.getElementById("one").value;
    document.getElementById("output").innerHTML = one;


    var two = document.getElementById("two").value;
    document.getElementById("output").innerHTML = two

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

0

Have you tried a for loop? you'd be able to add a click functionality with a closure or 'let' keyword or a separate function.. run the following in codepen, see how it works and if this is something that can be useful.


    function createButtons() {
       //let is block scoped, not function scoped
        for (let i = 1; i <= 5; i++) {
          var body = document.getElementsByTagName("BODY")[0];
          var button = document.createElement("BUTTON");
          button.innerHTML = 'Button ' + i;
          button.onclick = function() {
               alert('This is button ' + i);
          }
          body.appendChild(button);
        }
     }
      
     createButtons();

about 4 years ago · Juan Pablo Isaza Relatório

0

There is multiple solutions for this, but here a simple one: you can use the event data to get the info of the button clicked, then you can do what you want with these values.

HTML

<div id="output"></div>
<div class="numbers">
  <button value="1" id="one">1</button>
  <button value="2" id="two">2</button>
</div>

JS

document.querySelectorAll('.numbers button').forEach(button => { 
  button.addEventListener('click', (e) => {
    console.log(e.target.id, e.target.value)
  })
})
about 4 years ago · Juan Pablo Isaza Relatório

0

To display the output on clicking of numbers, you can pass in a this object inside the function like this

<button value="1" id="one" onclick="displayButtons(this)">1</button>

and when you click on it, you'll receive the button node inside the function full code would be

   <div class="numbers">
        <button value="1" id="one" onclick="displayButtons(this)">1</button>
        <button value="2" id="two" onclick="displayButtons(this)">2</button>
    </div>


    <script>
        function displayButtons(button) {
            document.getElementById("output").innerHTML += button.value
        }
    </script>

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