What is the best way to emulate an HTML input “maxlength” attribute on an HTML textarea?

后端 未结 8 1336
执笔经年
执笔经年 2020-11-28 11:54

An HTML text input has an attribute called \"maxlength\", implemented by browsers, which if set blocks user input after a certain number of characters.

An HTML texta

8条回答
  •  星月不相逢
    2020-11-28 12:40

    I figure I can give this a go, just another way of doing the same thing. I like this way of doing it because you could wrap this in some code to check if you're running in IE since maxlength does work on text areas in webkit and gecko browsers. It depends on the maxlength property being set on the textarea element in the html. Also because it actually works as the maxlength property works in the browser by default, preventing the user from adding more than the specified characters.

    $(document).ready(function () {
    
    
    $('textarea').on('keyup', function () {
        // Store the maxlength and value of the field.
        if (!maxlength) {
            var maxlength = $(this).attr('maxlength');
        }
        var val = $(this).val();
        var vallength = val.length;
    
        // alert
        if (vallength >= maxlength) {
    
    
            alert('Please limit your response to ' + maxlength + ' characters');
            $(this).blur();
        }
    
    
        // Trim the field if it has content over the maxlength.
        if (vallength > maxlength) {
            $(this).val(val.slice(0, maxlength));
        }
    });
    
    //remove maxlength on blur so that we can reset it later.
    $('textarea').on('blur', function () {
            delete maxlength;
        });
    });
    

提交回复
热议问题