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

Asked

Viewed 339 times

1

I am trying to make a calculator in Javascript and I want to click on a button the value is displayed on the screen. Another question is how do I concatenate the name of id of button with the content of for for I had added an event to each 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">

1 answer

2


The problem with your code is that part b+i.addEventListener, you are trying to concatenate a variable that does not exist b, with the value of i and trying to add a "this" event. You need to take the element you want to add the event, document.getElementById( ) and pass id as parameter that would be 'b'+i. Follows 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">

Browser other questions tagged

You are not signed in. Login or sign up in order to post.