How to print the value of a button in a text box using javascript

1

I'm trying to make a calculator in JavaScript and I want the value to appear on the screen when I click a button. Another question is how do I concatenate the name of id of button with index of for so I will add an event to every button .

var valor = [10];
//Aqui são armzenados os valores do button
for (var i = 0; i < 10; i++) {
  valor[i] = document.getElementById('b' + (i + 1)).value;
}

for (var i = 1; i <= 10; i++) {
  b + i.addEventListener('click', function() {

  });
}
button {
  width: 50px;
  height: 50px;
  margin-top: 5px;
  font-size: 20px;
}

input {
  height: 40px;
  font-size: 20px;
}
<button id="b1" value="1">1</button>
<button id="b2" value="2">2</button>
<button id="b3" value="3">3</button><br>
<button id="b4" value="4">4</button>
<button id="b5" value="5">5</button>
<button id="b6" value="6">6</button><br>
<button id="b7" value="7">7</button>
<button id="b8" value="8">8</button>
<button id="b9" value="9">9</button><br>
<button id="b10" value="0">0</button>
<button id="b11">+</button>
<button id="b12">-</button><br>
<button id="b13">/</button>
<button id="b14">x</button>
<button id="b15">=</button><br><br>
<input type="text" name="result" id="resultado">
    
asked by anonymous 25.07.2017 / 19:14

1 answer

2

The problem with your code is this b+i.addEventListener stretch, you are trying to concatenate a variable that does not exist b , with the value of i , and trying to add an "in" event. You need to get the element you want to add the event, document.getElementById( ) and pass the id as a parameter that would be 'b'+i . Here is the code below:

var result = document.getElementById('resultado')
var valor = [];
  //Aqui são armzenados os valores do button
  for (var i = 1; i <= 10; i++){
    valor[i] = document.getElementById('b'+ i).value;
  }

  for (var i = 1; i <= 10; i++) {
    document.getElementById('b'+i).addEventListener ('click', function () {
      result.value = this.value;
    });
  }
button {
  width: 50px;
  height: 50px;
  margin-top: 5px;
  font-size: 20px;
}
input {
  height: 40px;
  font-size: 20px;
}
<button id="b1" value="1">1</button>
<button id="b2" value="2">2</button>
<button id="b3" value="3">3</button><br>
<button id="b4" value="4">4</button>
<button id="b5" value="5">5</button>
<button id="b6" value="6">6</button><br>
<button id="b7" value="7">7</button>
<button id="b8" value="8">8</button>
<button id="b9" value="9">9</button><br>
<button id="b10" value="0">0</button>
<button id="b11">+</button>
<button id="b12">-</button><br>
<button id="b13">/</button>
<button id="b14">x</button>
<button id="b15">=</button><br><br>
<input type="text" name="result" id="resultado">
    
25.07.2017 / 19:29