简体   繁体   中英

If I have 45 buttons (numbers) and I have to choose 6 numbers, how can I make my 6 clicked buttons go to my 6 inputs numbers

If I have 45 buttons (numbers) and I have to choose 6 numbers, how can I make my 6 clicked buttons go to my 6 inputs numbers, that is I mean for each click on a button, send this value to an input type number

I clicked on the first button and I did the function of calling the input id = "chk1" to the first inbox innerHTML.value = "", but how do I make the second clicked button go to the second input?

21 22

    <script type="text/javascript">
         function botonear() {
          document.getElementById("chk1").value= 21;
         }
          function botonear2() {
          document.getElementById("chk2").value= 22;
         }
       </script>

I expect click in any button and send it to the first empty input, then second click in different button goes to the second empty input and so..

Assuming you have myButtons and myInputs as arrays of your buttons and inputs respectively, you can:

1) use using addEventListener to attach event listeners to each button and detect clicks; and

2) use array.prototype.find to find your first empty input and update its value.

myButtons.forEach((button, i) =>
    button.addEventListener('click', () => {
      let firstEmptyInput = myInputs.find(input => !input.value);
      if (firstEmptyInput)
        firstEmptyInput.value = i;
    }));

[1] addEventListener https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

[2] find : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find `

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM