Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading