skip to Main Content

I’m trying to build a calculator and I want to get the values of the clicked buttons in the textbox

this just an example how can I get the values of the clicked buttons here



<input type="text" name="" id="textfield" placeholder="Text" class="Text" readonly><br>
<button class="Y" value="Y"  onclick="">Y</button>
<button class="A" value ="A" onclick="">A</button>
<button class="S" value ="S" onclick="">S</button>
<button class="I" value ="I" onclick="">I</button>
<button class="R" value ="R" onclick="">R</button>

2

Answers


  1. Here you can use javascript to handle this type of functionality . For Example :

    function appendValue(value) {
      var textfield = document.getElementById("textfield");
      textfield.value += value;
    }
    <input type="text" name="" id="textfield" placeholder="Text" class="Text" readonly><br>
    <button class="Y" value="Y" onclick="appendValue('Y')">Y</button>
    <button class="A" value ="A" onclick="appendValue('A')">A</button>
    <button class="S" value ="S" onclick="appendValue('S')">S</button>
    <button class="I" value ="I" onclick="appendValue('I')">I</button>
    <button class="R" value ="R" onclick="appendValue('R')">R</button>
    Login or Signup to reply.
  2. You don’t have to set value in button. Check this JSFiddle

    Anyway, here’s snippet for approach with button’s value:

    const buttons = document.querySelectorAll('button');
    const input = document.getElementById("textfield");
    
    let text = "";
    
    
    buttons.forEach(btn => btn.addEventListener("click", () => {
        text = text.concat(btn.value)
            input.value = text;
    }))
    <input type="text" name="" id="textfield" placeholder="Text" class="Text" readonly><br>
    <button class="Y" value="Y"  onclick="">Y</button>
    <button class="A" value ="A" onclick="">A</button>
    <button class="S" value ="S" onclick="">S</button>
    <button class="I" value ="I" onclick="">I</button>
    <button class="R" value ="R" onclick="">R</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search