headache
headache

Reputation: 133

js loses chars if typed too quickly

OK, I got this completed and working and I've removed mention of some of the issues I had to assist with easy reading.

I am obfuscating the characters entered to a text box (id='user_pin_code') such that they appear to be ' * ' or ' **** ' according to the number of chars. It's for the entry of a PIN code.

The first part takes the chars entered and replaces each with an ' * ' asterisk. So a 6 char PIN will show ' ****** ' All good so far, regardless of how quickly I type.

The next part takes the actual chars entered and populates another textbox (id='PINcode'), with the actual characters entered. Trouble is, if I type quickly some are missed out. so 'wxymdo' can be entered as 'wxmd'.

<script>
$(document).ready(function(e) {

var actualTextEntered = ""; 


    $("#user_pin_code").keyup(function(e) {
                       
        var x = document.getElementById("user_pin_code").value;
                
        actualTextEntered += x.replace(/\\*/g,"");
                
        addEventListener('keydown', function(event) {
            const key = event.key; // const {key} = event; ES6+
            if ( key === "Backspace" ) {
                // Do something
                actualTextEntered = ''; 
                x='';
            }
        });
        
        
        
        document.getElementById("user_pin_code").value = "";
        
        for (var i=0;i<actualTextEntered.length;i++)
        {   
        document.getElementById("user_pin_code").value += "*";
        document.getElementById("PINcode").value = actualTextEntered;
        }   
        
        
    });

});

Upvotes: 1

Views: 122

Answers (1)

Fritzdultimate
Fritzdultimate

Reputation: 460

The problem is just how the keyup event works, it tends not to be able capture some very fast inputs. Just the way onmousemove works, when the mouse moves very fast, some element will be skipped.

Why not use input type="password" or I think using oninput event can be a work around for you.

Upvotes: 4

Related Questions