Thomas Christopher Davies Thomas Christopher Davies - 1 month ago 5
HTML Question

jQuery: Preventing multiple inputs at a time

I am writing a jquery code which should switch the input chars with chars I defined in a variable. So far the code works nicely if you carefully only press one char at a time. But as soon as you hit multiple chars at once you start breaking the result. What kind of options are there to make jquery either only take one char at a time or properly read out and convert multiple chars.

The results of multiple chars pressed too fast or pressed similarly result in having the string of the variable having chars mixed up or/and having some chars from the multiple inputs mixed in.

I learned already about the .prop() function to disable input, but even if I disable Input I cannot prevent multiple chars being passed into the function.

Thank you guys in advance,
cheers

HTML:



jQuery(document).ready(function(){
String.prototype.removeChar = function(){
var string = "";
for(var i = 0, length = this.length-1; i<length; i++){
string += this.charAt(i);
}
return string;
}
var name = "Some Random Name",
length,
sub = "",
event,
array=[];
$("form").on("keyup", function(e){
event = e.keyCode;
if (e.keyCode === 8){
length = $(".input").val().length;
sub = sub.removeChar();
$(".input").val(sub);
}else{
length = $(".input").val().length;
sub += name.charAt(length-1);
$(".input").val(sub);
}
});

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>Who should be President?<input type="text" name="president" class="input"></form>




Answer

Just change

  sub += name.charAt(length-1);

to

sub = name.substring(0, length);

Idea is to just get the total number of characters typed by the user and fetch that many characters from the name variable using substring function

jQuery(document).ready(function(){
        String.prototype.removeChar = function(){
            var string = "";
            for(var i = 0, length = this.length-1; i<length; i++){
                string += this.charAt(i);
            }
            return string;
        }
        var name = "Some Random Name",
            length,
            sub = "",
            event,
            array=[];
        $("form").on("keyup", function(e){
            event = e.keyCode;
            if (e.keyCode === 8){
                length = $(".input").val().length;
                sub = sub.removeChar();
                $(".input").val(sub);
            }else{
                length = $(".input").val().length;
                sub = name.substring(0, length);  // this is the change
                $(".input").val(sub);
                }
        });
        
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>Who should be President?<input type="text" name="president" class="input"></form>

Comments