Skip to content
Advertisement

typing in two inputs using same keypad

i have an HTML and javasscript Keypad to typing Numbers into input using keypad im trying to add more inputs this keypad working good with only one input

How i make my code javascript work with second input too when i focused on it the keypad should be able to typing in second input using same keypad?

        function resetNumber()
      {
          document.getElementById("field").value = '';
      }
      
      function setNumber(number) {
        document.getElementById("field").value = document.getElementById("field").value === number ?  '' : document.getElementById("field").value += number;
      }
<html>
<head>
    <script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
</head>
<body>
    <html>
<body>
    <button onclick="resetNumber()">Reset</button>
   <button onclick="setNumber(0)">0</button>
    <button onclick="setNumber(1)">1</button>
    <button onclick="setNumber(2)">2</button>
    <button onclick="setNumber(3)">3</button>
    <button onclick="setNumber(4)">4</button>
    <button onclick="setNumber(5)">5</button>
    <button onclick="setNumber(6)">6</button>
    <button onclick="setNumber(7)">7</button>
    <button onclick="setNumber(8)">8</button>
    <button onclick="setNumber(9)">9</button>
    <br />
        <input type="text" id="field" />
        <input type="text" id="second" />
</body>
</html>

Advertisement

Answer

I would suggest storing the active input in a variable when one of them is focused:

let activeInput;

document.querySelector("#field").addEventListener("focus", (event) => {
  activeInput = event.target;
});

document.querySelector("#second").addEventListener("focus", (event) => {
  activeInput = event.target;
});

function resetNumber() {
  if (!activeInput) {
    console.log("select an input!");
    return;
  }
  activeInput.value = "";
}
function setNumber(number) {
  if (!activeInput) {
    console.log("select an input!");
    return;
  }
  activeInput.value = activeInput.value === number ? "" : (activeInput.value += number);
}

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement