简体   繁体   中英

Text input allows for more than 3 characters

I have an input where the user can enter initials. The input has a max length of 3.

I have the following js

    personaliseShirt.plInitials = function () {
        console.log('pressed');
        var inputPL = $('.max-length_3');

        $(inputPL).on('keyup', function () {
            var max = 3;
            console.log(inputPL.val.length);
            if (inputPL.val.length > max) {
                inputPL.val = inputPL.value.substring(0, max);
            }
        })
    }

My issue is that the first input field seems to stop the user from entering more than 3 characters but if the user has multiple, then after the first input the rest allow for more than 3 :/

HTML for input field

<input onkeyup="this.value = this.value.toUpperCase();" pattern="[A-Za-z]+" maxlength="3" type="text" class="form-control input-block-level defaultY? max-length_3" max="3" value="" placeholder="Enter Player Initials" name="player_2_9_6" id="player_2_9_6">

Any help or suggestions would be great

Thanks in advance!

Your variable inputPL is a JQuery array with multiple elements in it. In your keyup handler, you check for the length of this array, which won't work. Use this instead:

personaliseShirt.plInitials = function () {
    console.log('pressed');
    var inputPL = $('.max-length_3');

    $(inputPL).on('keyup', function () {
        var max = 3;
        var $thisElem = $(this);
        console.log($thisElem.val.length);
        if ($thisElem.val.length > max) {
            $thisElem.val = $thisElem.value.substring(0, max);
        }
    })
}

Also please check, if your mix-up of val and value is intended, or if you need to use val() instead.

It's working on firefox and chrome. You can use this function for repeated use.

$('input.testinput').on('keyup', function() {
    limitText(this, 3)
});

function limitText(field, maxChar){
    var ref = $(field),
        val = ref.val();
    if ( val.length >= maxChar ){
        ref.val(function() {
            console.log(val.substr(0, maxChar))
            return val.substr(0, maxChar);       
        });
    }
}

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM