Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - keyup sometimes firing twice

Why keyup sometimes firing twice?

I followed to use unbind and bind but seems not working.

My code [HTML]:

   <div id="otpmsg" class="error-otp text-center"></div>
    <div id="otp" name="otp" class="form-group text-center">
     <input class="m-2 text-center otp-control otp-control-solid" type="text" id="first" maxlength="1" />
     <input class="m-2 text-center otp-control otp-control-solid" type="text" id="second" maxlength="1" />
     <input class="m-2 text-center otp-control otp-control-solid" type="text" id="third" maxlength="1" />
     <input class="m-2 text-center otp-control otp-control-solid" type="text" id="fourth" maxlength="1" />         
    </div>

Javascript part:

    $('#otp').unbind('keyup');
      $('#otp').bind('keyup', function (e) {
        e.preventDefault();
        const inputs = document.querySelectorAll('#otp > *[id]');
        let compiledOtp = '';
            for (let i = 0; i < inputs.length; i++) {
                compiledOtp += inputs[i].value;
            }
        otp = compiledOtp;
          if(otp.length == 4) {
          ....
question from:https://stackoverflow.com/questions/65878424/keyup-sometimes-firing-twice

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

1 Answer

0 votes
by (71.8m points)

keyup event is triggered when a key is released. When a key combination is used (e.g. Shift + Tab) the event will be triggered two or more times depending on the key combination used.

The keyup event will be triggered twice for the key combination Shift + Tab. One event for the Shift and one event for the Tab.

You can handle this case by writing a condition in the callback function to allow only numbers (considering the OTP will be numeric) by taking the value of the key pressed by the user using the event.key property.

$("#otp").on("keyup", function (e) {
  e.preventDefault();

  const pressedKey = e.key;
  if (!/^[0-9]+$/.test(pressedKey)) {
    return;
  }

  const inputs = document.querySelectorAll("#otp > *[id]");
  let compiledOtp = "";
  for (let i = 0; i < inputs.length; i++) {
    compiledOtp += inputs[i].value;
  }
  otp = compiledOtp;
  if (otp.length == 4) {
  ...
});

For more information, please refer to the documentation https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...