首页 > 解决方案 > How to set focus on next input when the button "Enter" is pressed? (javascript)

问题描述

I need some advice.

I have created a function where when spacebar is pressed, it'll create a new input field. What i would like to know is how to set focus on the input field that has been created when spacebar is pressed.

Thanks in advance.

Here is my code: (HTML included)

<div id="paper">
  <div id="content">
  <input type="text" class="input1">
  </div>
  </div>

Javascript:

'use strict';

const input1 = document.querySelector('.input1');
const add = input1.addEventListener('keydown', function(e){
        if((e.keyCode === 13)){
        return mover();
        }
      });

 const mover = function(){
  const mega = document.createElement('input');
  const content = document.getElementById('content');
  content.appendChild(mega);
  mega.style.border = "0px solid";
  mega.style.marginTop = "75px";
  mega.style.width = "600px";
}

标签: javascriptinputfocuscreateelement

解决方案


像这样的东西,可以做的伎俩。

const container = document.getElementById("inputs-container");
let inputs = document.getElementsByTagName("input");

// Add input on press Enter
document.onkeyup = (evt) => {
  if (evt.keyCode == 32) {
    let input = document.createElement("input");
    input.type = "text";
    input.placeholder = "Input...";
    input.onkeyup = inputOnEnter;
    container.appendChild(input);
    inputs = document.getElementsByTagName("input");
  }
};

// Focus next input on Space
const inputOnEnter = (evt) => {
  if (evt.keyCode == 13) {      
    let index = Object.keys(inputs).filter(a => inputs[a] === evt.target);
    let nextIndex = parseInt(index) + 1;

    if (inputs[nextIndex]) inputs[nextIndex].focus();
  }
};

for (let i = 0; i < inputs.length;i++) {
  inputs[i].onkeyup = inputOnEnter;
}
<div id="inputs-container">
  <input type="text" placeholder="Input..." />
</div>


推荐阅读