Skip to content
Advertisement

Populate next empty text input based on a button click

I have a simple set of buttons that may be clicked in any order. When clicked the button should fill the next available text box.

So far I have only been able to make the button click populate the text box that is in focus. This only really fulfils half of my task.

At the moment I am only looking for vanilla JS solutions rather than JQuery if possible.

<body>
  <div class="buttons">
    <button class="btn" id="txt1" onclick="addText('txt1')">txt1</button>
    <button class="btn" id="txt2" onclick="addText('txt2')">txt2</button>
    <button class="btn" id="txt3" onclick="addText('txt3')">txt3</button>
    <button class="btn" id="txt3" onclick="addText('txt3')">txt3</button>
    <button class="btn" id="txt4" onclick="addText('txt4')">txt4</button>
    <button class="btn" id="txt5" onclick="addText('txt5')">txt5</button>
  </div>

  <div class="textBoxes">
    <input type="text" class="inputs" id="box1" placeholder="WPT 1" onfocus="field=this;" autofocus/>
    <input type="text" class="inputs" id="box2" placeholder="WPT 2" onfocus="field=this;"/>
    <input type="text" class="inputs" id="box3" placeholder="WPT 3" onfocus="field=this;"/>
    <input type="text" class="inputs" id="box4" placeholder="WPT 4" onfocus="field=this;"/>
    <input type="text" class="inputs" id="box5" placeholder="WPT 5" onfocus="field=this;"/>
  </div>

  <script>
    var field = 0;
    function addText(txt){
      if(field === 0) return false;
      field.value = txt;
    }
  </script>
</body>

Advertisement

Answer

You can add a paramater to your function to update exact text box like this:

function addText(txt, fieldNumber) {
  var elems = document.getElementsByClassName("inputs");
  if (elems.length <= fieldNumber) return;
  elems[fieldNumber].value = txt;
}

and then call it like “addText(‘text’, 3)”

Check this sandbox https://codesandbox.io/s/laughing-einstein-byhf0f?file=/src/index.js:299-472

If by “next available”, you meant a field which doesn’t already have a value then edit your function like this:

function addText(txt) {
  var elems = document.getElementsByClassName("inputs");
  console.log("111");
  console.log(elems);
  for (let i = 0; i < elems.length; i++) {
    if (elems[i] && !elems[i].value) {
      elems[i].value = txt;
      break;
    }
  }
}

For a demo check this sandbox: https://codesandbox.io/s/trusting-browser-lckvy0?file=/index.html

Advertisement