[javascript] textarea character limit

I would like to be able to limit the number of characters in a textarea. The method I am using works great in Google Chrome, but is slow in Firefox, and doesn't work in IE.

Javascript:

function len(){
  t_v=textarea.value;
  if(t_v.length>180){
    long_post_container.innerHTML=long_post;
    post_button.className=post_button.className.replace('post_it_regular','post_it_disabled');
    post_button.disabled=true;
  }
  else{
    long_post_container.innerHTML="";
    post_button.className=post_button.className.replace('post_it_disabled','post_it_regular');
    post_button.disabled=false;
  }
  if(t_v.length>186){
        t_v=t_v.substring(0,186);
    }
}

HTML:

<textarea id="user_post_textarea" name="user_post_textarea" cols="28" rows="1"  onkeypress="len();" onkeyup="len();"></textarea>

Javascript at bottom of body element:

textarea=document.getElementById('user_post_textarea');

This question is related to javascript html textarea cross-browser

The answer is


... onkeydown="if(value.length>500)value=value.substr(0,500); if(value.length==500)return false;" ...

It ought to work.


Try using jQuery to avoid cross browser compatibility problems...

$("textarea").keyup(function(){
    if($(this).text().length > 500){
        var text = $(this).text();
        $(this).text(text.substr(0, 500));   
    }
});

using maxlength attribute of textarea would do the trick ... simple html code .. not JS or JQuery or Server Side Check Required....


This is entirely untested but it should do what you need.

Update : here's a jsfiddle to look at. Seems to be working. link

You would past it into a js file and reference it after your jquery reference. You would then call it like this..

$("textarea").characterCounter(200);

A brief explanation of what is going on..

On every keyup event the function is checking what type of key is pressed. If it is acceptable the the counter will check the count, trim any excess and prevent any further input once the limit is reached.

The plugin should handle pasting into the target too.

  ; (function ($) {
        $.fn.characterCounter = function (limit) {
            return this.filter("textarea, input:text").each(function () {
                var $this = $(this),
                  checkCharacters = function (event) {

                      if ($this.val().length > limit) {

                          // Trim the string as paste would allow you to make it 
                          // more than the limit.
                          $this.val($this.val().substring(0, limit))
                          // Cancel the original event
                          event.preventDefault();
                          event.stopPropagation();

                      }
                  };

                $this.keyup(function (event) {

                    // Keys "enumeration"
                    var keys = {
                        BACKSPACE: 8,
                        TAB: 9,
                        LEFT: 37,
                        UP: 38,
                        RIGHT: 39,
                        DOWN: 40
                    };

                    // which normalizes keycode and charcode.
                    switch (event.which) {

                        case keys.UP:
                        case keys.DOWN:
                        case keys.LEFT:
                        case keys.RIGHT:
                        case keys.TAB:
                            break;
                        default:
                            checkCharacters(event);
                            break;
                    }   

                });

                // Handle cut/paste.
                $this.bind("paste cut", function (event) {
                    // Delay so that paste value is captured.
                    setTimeout(function () { checkCharacters(event); event = null; }, 150);
                });
            });
        };
    } (jQuery));

I believe if you use delegates, it would work..

$("textarea").on('change paste keyup', function () {
    var currText = $(this).val();
    if (currText.length > 500) {
        var text = $(this).text();
        $(this).text(text.substr(0, 500));
        alert("You have reached the maximum length for this field");
    }
});

I think that doing this might be easier than most people think!

Try this:

var yourTextArea = document.getElementById("usertext").value;
// In case you want to limit the number of characters in no less than, say, 10
// or no more than 400.        
    if (yourTextArea.length < 10 || yourTextArea.length > 400) {
        alert("The field must have no less than 10 and no more than 400 characters.");
        return false;
    }

Please let me know it this was useful. And if so, vote up! Thx!

Daniel


This works on keyup and paste, it colors the text red when you are almost up to the limit, truncates it when you go over and alerts you to edit your text, which you can do.

var t2= /* textarea reference*/

t2.onkeyup= t2.onpaste= function(e){
    e= e || window.event;
    var who= e.target || e.srcElement;
    if(who){
        var val= who.value, L= val.length;
        if(L> 175){
            who.style.color= 'red';
        }
        else who.style.color= ''
        if(L> 180){
            who.value= who.value.substring(0, 175);
            alert('Your message is too long, please shorten it to 180 characters or less');
            who.style.color= '';
        }
    }
}

Quick and dirty universal jQuery version. Supports copy/paste.

$('textarea[maxlength]').on('keypress mouseup', function(){
    return !($(this).val().length >= $(this).attr('maxlength'));
});

I have written my method for this, have fun testing it on your browsers, and give me feedback.

cheers.

function TextareaControl(textarea,charlimit,charCounter){
    if(
            textarea.tagName.toLowerCase() === "textarea" && 
            typeof(charlimit)==="number" &&
            typeof(charCounter) === "object" && 
            charCounter.innerHTML !== null
    ){
        var oldValue = textarea.value;
        textarea.addEventListener("keyup",function(){
            var charsLeft = charlimit-parseInt(textarea.value.length,10);
            if(charsLeft<0){
                textarea.value = oldValue;
                charsLeft = charlimit-parseInt(textarea.value.length,10);
            }else{
                oldValue = textarea.value;
            }
            charCounter.innerHTML = charsLeft;
        },false);
    }
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to textarea

Get user input from textarea Set textarea width to 100% in bootstrap modal Remove scrollbars from textarea Add a scrollbar to a <textarea> Remove all stylings (border, glow) from textarea How to clear text area with a button in html using javascript? Get value from text area What character represents a new line in a text area Count textarea characters More than 1 row in <Input type="textarea" />

Examples related to cross-browser

Show datalist labels but submit the actual value Stupid error: Failed to load resource: net::ERR_CACHE_MISS Click to call html How to Detect Browser Back Button event - Cross Browser How can I make window.showmodaldialog work in chrome 37? Cross-browser custom styling for file upload button Flexbox and Internet Explorer 11 (display:flex in <html>?) browser sessionStorage. share between tabs? How to know whether refresh button or browser back button is clicked in Firefox CSS Custom Dropdown Select that works across all browsers IE7+ FF Webkit