Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu December 29, 2022 › #Button #HowTo

How to create buttons with numbers from 0-9 that adds into a textbox

So, in this article, we are going to create buttons with numbers from 0-9 that adds into a textbox when we press them.

Basically, we will create a numeric keyboard with numbers 0-9. Suppose, you press 7,5, and 4. Then, the final result will display 754 in the input field.

<input id="display" type="text">
<button onclick="addNumber(0)">0</button>
<button onclick="addNumber(1)">1</button>
<button onclick="addNumber(2)">2</button>
<button onclick="addNumber(3)">3</button>
<button onclick="addNumber(4)">4</button>
<button onclick="addNumber(5)">5</button>
<button onclick="addNumber(6)">6</button>
<button onclick="addNumber(7)">7</button>
<button onclick="addNumber(8)">8</button>
<button onclick="addNumber(9)">9</button>

We have created an input element with id display and ten button elements with numbers 0-9.

We have also included the onclick attribute to the button elements and set its value to addNumber(). We have passed current value to the addNumber() function. So that we can access later.

<script>
 function addNumber(n){
  const display = document.querySelector('#display');
  display.value += n
 }
</script>
  1. We have created the addNumber() function and passed n as a parameter that returns the current number.
  2. Then, we have selected the input element and stored in a variable named display.
  3. Finally, we have added the input value plus the current value.
save
listen
AI Answer
Write Your Answer
loading
back
View All