Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 6 of 6
  1. #1
    Regular Coder
    Join Date
    Nov 2011
    Posts
    154
    Thanks
    5
    Thanked 0 Times in 0 Posts

    textarea character limit?

    Hello, how could I limit the number of characters that can be typed inside a textarea? Apparently 'maxlength' doesn't work in IE. I'm looking for a cross-browser solution. I don't think it's possible to do with only CSS, so I hope there is a way to do with JS, or jQuery even?

    Actually, more preferably, if there is a way to limit the typing not by the number of characters, but simply by the width and height set for the textarea. Say I have a textarea 200px x 200px , and once I reach the very end of the last line (without any scrolling/overflow), I want to not be able to type anymore. Is there a cross-browser solution for this?

  • #2
    Regular Coder Nile's Avatar
    Join Date
    Jun 2008
    Posts
    280
    Thanks
    2
    Thanked 46 Times in 46 Posts
    For just a maxlength, you can do:
    Code:
    window.onload = function() {
        var textareas = document.getElementsByTagName("textarea");
        for (var i = 0; i < textareas.length; i++) {
            textareas[i].onkeydown = textareas[i].onblur = textareas[i].onfocus = function() {
                if (this.value.length > Number(this.getAttribute("maxlength"))) {
                    this.value = this.value.substring(0, Number(this.getAttribute("maxlength")));
                }
            };
        }
    };​
    This will enable the maxlength attribute to work in any browser that supports javascript. As for making the user only able to type in order to fill the textarea, have you considered the browsers that allow resizable textareas? The idea is doable, but overall a bad idea. If you're still considering and another member hasn't already posted a solution, reply back and I'll get you one.

  • #3
    Senior Coder jmrker's Avatar
    Join Date
    Aug 2006
    Location
    FL
    Posts
    3,086
    Thanks
    38
    Thanked 498 Times in 492 Posts

  • #4
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,017
    Thanks
    203
    Thanked 2,538 Times in 2,516 Posts
    Quote Originally Posted by Nile View Post
    For just a maxlength, you can do:
    Code:
    window.onload = function() {
        var textareas = document.getElementsByTagName("textarea");
        for (var i = 0; i < textareas.length; i++) {
            textareas[i].onkeydown = textareas[i].onblur = textareas[i].onfocus = function() {
                if (this.value.length >= Number(this.getAttribute("maxlength"))) {
                    this.value = this.value.substring(0, Number(this.getAttribute("maxlength") -1));
                }
            };
        }
    };​
    This will enable the maxlength attribute to work in any browser that supports javascript. As for making the user only able to type in order to fill the textarea, have you considered the browsers that allow resizable textareas? The idea is doable, but overall a bad idea. If you're still considering and another member hasn't already posted a solution, reply back and I'll get you one.
    The user can still paste text longer than the maximum number of characters into the textarea.

    To block this you need:-

    Code:
    function OnPaste () {
    return false;   // cancels (blocks)  the onpaste event.
    setTimeout(checkMaxInput,100);  // delay is necessary
    }
    and for the <textarea> onpaste="OnPaste ()"

    But the simplest solution to number of characters limit is:-

    Code:
    <script type="text/javascript"> 
    function imposeMaxLength(Object, MaxLen) { 
    return (Object.value.length <= MaxLen); 
    } 
    </script>  
     
    <textarea name="txt1" onkeypress="return imposeMaxLength(this, 15);" ></textarea>
    Obviously all these approaches only work where Javascript is enabled in the browser. So it is absolutely essential to repeat the check server-side.

    I am unclear why resin requires this unusual limitation anyway.
    Last edited by Philip M; 07-01-2012 at 11:00 AM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #5
    Regular Coder
    Join Date
    Nov 2011
    Posts
    154
    Thanks
    5
    Thanked 0 Times in 0 Posts
    Nile, I would like a solution for making the user only able to type in order to fill the textarea, if you are still willing. I've disabled the resize feature, and have set the textarea font to a specific font type, size, and line-height, which should help keep consistency across browsers.

    Philip, your solution does work great for setting limit on number of characters, but the more I think about it I really do want the characters to be limited by the textarea's width and height, or even by number of lines. Because while 500 characters may fill up the entire space in one instance, it may fill less/more space the next time depending on the individual characters used and their width. This will be a stand alone textarea used as sort of a notepad. And for visual appeal, I don't want to use a scrollbar, instead there will be the option to turn to the next page when the first gets filled.

    I've looked at several scripts related to this sort of thing, and the closest one I've found to what I'm looking for is this. But I don't like the fact that it lets you enter the 'restricted' character/line, and then deletes the last character/line in the textarea. Mainly because if you go back to add something to a previous line and in the process create a new line, then the last line/character in the textarea automatically gets deleted. Perhaps there's a way to modify this, so that instead of creating and then deleting the new 'restricted' line/character, it simply just won't create it in the first place. In other words when you've reached the limit, and go to type another character or press Enter, nothing happens.

    Code:
    function limitTextarea(textarea,maxLines,maxChar)
     {
     var lines=textarea.value.replace(/\r/g,'').split('\n'),
     lines_removed,
     char_removed,
     i;
     if(maxLines&&lines.length>maxLines)
     {
     lines=lines.slice(0,maxLines);
     lines_removed=1
     }
     if(maxChar)
     {
     i=lines.length;
     while(i-->0)if(lines[i].length>maxChar)
     {
     lines[i]=lines[i].slice(0,maxChar);
     char_removed=1
     }
     if(char_removed||lines_removed)
     {
     textarea.value=lines.join('\n')
     }
     function watchTextarea()
     {
     document.getElementById('restictable').onkeyup()
     }
     }
     }
    
    onkeyup="limitTextarea(this,6,40)" onfocus="focus_watch=setInterval('watchTextarea()',250)" onblur="clearInterval(focus_watch)"
    I'm also not exactly sure what that watchTextarea function is doing. Tried changing 'restictable' (set by author) to my textarea id but nothing seemed to change. This script does seem a bit messy and problematic, so I'm definitely interested in what you can come up with Nile, or anyone else?

  • #6
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,640
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Just remember that any limit you apply with JavaScript can be easily bypassed by anyone without JavaScript so you will still need to retest on the server.

    For that same reason it is not necessary to get too fancy trying to block all of the different ways that more data might be input from JavaScript as the server side block will catch any that bypass what JavaScript you do provide. The JavaScript is there for the convenience of those filling in the field.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •