Search code examples
javascripteventsmobilekeydownpreventdefault

How can I prevent user Input to be shown on input filed in mobile browser


I want a user to input his name, but I want to limit the amount of characters to 15, in the desktop browsers it works.

document.querySelector('#input-name').addEventListener('keydown', function (e) {

const maxLetters = 15

document.querySelector('#input-name').addEventListener('keyup', function (e) {
    userName = e.target.value
    document.querySelector('#labelInputName').textContent = userName.length + "/" + maxLetters

})

userName = e.target.value

if (userName.length >= maxLetters && e.keyCode != 46 && e.keyCode != 8) {
    e.preventDefault();
}

else if (e.keyCode != 46 && e.keyCode != 8) {
    document.querySelector('#labelInputName').textContent = userName.length + 1 + "/" + maxLetters
}

})

So in the desktop browser it works after I am getting to 15/15 pressing any key from the keyboard except Delete and BackSpace won't do anything(won't even show the 16 character in the input field)...

But in the mobile browser I am getting to 15/15 and than keep going 16/15.... How can I fix that?


Solution

  • By far, the most cross-browser way to do this is with the maxlength attribute of the input element; no JavaScript required:

    <input id="input-name" maxlength="15">
    

    Live Example:

    <input id="input-name" maxlength="15">

    maxlength has been part of HTML basically forever (it's in the HTML+ spec from 1993), I expect browser support for it is universal.

    If you need to set the max length from JavaScript, you'd use the maxLength property:

    document.getElementById("input-name").maxLength = 15;
    

    Live Example:

    document.getElementById("input-name").maxLength = 15;
    <input id="input-name">