Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
108 views
in Technique[技术] by (71.8m points)

javascript - How to set default input for input keypress?

I have a webpage written in React (but it should not be strictly relevant to that question) that is composed by several inputs, let's call them Name, Surname and Code.

To work quickly, the insertion of the code is done with a Barcode Scanner that works as external keyboard. My idea is that if some field is focused, the keypress is inserted in the focused input but, in case no input is focused, I want to automatically focus and fill the Code input.

Is there a way to that it easily?

question from:https://stackoverflow.com/questions/65642110/how-to-set-default-input-for-input-keypress

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

let inputName = document.querySelector('input[name="name"]');
let inputSurname = document.querySelector('input[name="surname"]');
let inputCode = document.querySelector('input[name="code"]');

let focusedInput = null;

[inputName, inputSurname, inputCode].forEach((input) => {
  input.addEventListener('blur', () => {
    focusedInput = null;
  });
  input.addEventListener('focus', () => {
    focusedInput = input;
  });
});

document.body.addEventListener('keypress', () => {
  if (focusedInput == null) {
    inputCode.focus();
  }
});
<div>
  <label>Name</label>
  <input type="text" name="name" />
</div>
<div>
  <label>Surname</label>
  <input type="text" name="surname" />
</div>
<div>
  <label>Code</label>
  <input type="text" name="code" />
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...