Since they are functions that do practically the same thing, where the only thing that changes is the value to add according to the button that is pressed, you could simplify the code considerably if you better organize each button and its attributes.
For this:
- To the buttons , we will assign them the same class, which I have called
btnNumber
(in this way we can add a listener to all of them by means of their class and their type). Consequently, we will no longer need to invoke a function for each button pressed, so we remove the onclick
of each button.
- We will also give an attribute
value
to each button, this value will be very useful, as you will see later
- We will use
querySelectorAll
to select the buttons and assign them the listener (there would be other ways to do it in case of compatibility problems). This will allow us to invoke a single function each time one of those buttons is pressed.
- In the function to which I have called
agregarTexto
, we take the value
of the button that was pressed by using this
, and we add it to the input concatenating with +=
.
In this way the code is much simplified.
NOTE: I assumed that the initial value 0
you had was not interested in saving it, so it has been changed to placeholder
, which does not affect the values of input
. If you are interested in keeping the 0
on the left, you change the placeholder
by value="0"
as you originally had it.
I hope it serves you.
document.querySelectorAll("button.btnNumber").forEach(function(elem) {
elem.addEventListener('click', agregarTexto, false);
});
function agregarTexto() {
var btnValor = this.value;
var elInput = document.getElementById("inputext");
elInput.value += btnValor;
}
<div class="display">
<input type="number" id="inputext" placeholder="0">
</div>
<br />
<button class="btnNumber" value="1">1</button>
<button class="btnNumber" value="2">2</button>
<button class="btnNumber" value="3">3</button>