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

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

    Use a JavaScript framework (Prototype, jQuery, etc.) so that you have cross-browser event support. Write a one liner on keyup to prevent the user from entering the maxlength.

    Note: You'll also have to check that length server side.

    0 讨论(0)
  • 2020-11-28 12:58

    I found a nice script here that stops the user from entering more text after the length of the input string exceeds the MaxLen parameter, it has the undeniable benefit of mostly staying out of the user's face.

    My problem with that script was that it also blocked the navigation keys(arrows, home, end) along with backspace and delete, so I modified it slightly, otherwise the user couldn't delete the text he entered if he reached the limit set by MaxLen (which would be kind of hilarious :P).

    Javascript:

    function imposeMaxLength(Event, Object, MaxLen)
    {
            return (Object.value.length <= MaxLen)||(Event.keyCode == 8 ||Event.keyCode==46||(Event.keyCode>=35&&Event.keyCode<=40))
    }
    

    And the HTML that goes with it:

    <textarea onkeypress="return imposeMaxLength(event, this, 110);" rows="4" cols="50">
    

    The user can still get around this limitation by pasting text into the textarea, but that can be easily solved inside imposeMaxLength.

    0 讨论(0)
提交回复
热议问题