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

后端 未结 8 1341
执笔经年
执笔经年 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:53

    PPK's Textarea Maxlength script is available on his site. Nothing fancy, just plain old JavaScript.

    You can easily use this as a starting point and make changes to accommodate your CSS "notification" requirement.

    Note that the author states: "The purpose of my script is not to enforce the maximum length, though it can easily be changed to do that. However, I decided to restrict my script to giving a polite reminder when the user exceeds the maximum amount of characters."

    UPDATE: Due to linkrot on the attached article, here is the code that once existed on that link:

    HTML:

    
    

    JS:

    function setMaxLength() {
        var x = document.getElementsByTagName('textarea');
        var counter = document.createElement('div');
        counter.className = 'counter';
        for (var i=0;i maxLength)
            this.relatedElement.className = 'toomuch';
        else
            this.relatedElement.className = '';
        this.relatedElement.firstChild.nodeValue = currentLength;
        // not innerHTML
    }
    

    Simply call the setMaxLength(); function on load.

提交回复
热议问题