15

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 textarea element, on the other hand, does not have this attribute. My goal is to emulate the behavior of maxlength on an HTML textarea. Requirements:

  • At a minimum, show (CSS change) that the user typed in too many characters.
  • Ideally, block the user from typing more characters, as happens on an HTML input.

It is understood that server-side validation should check the length again. Here I am focusing on the client-side part only.

My question is: what is the cleanest client-side way of emulating maxlength on an HTML textarea? Ideally, point to a proven, open source, piece of JavaScript that you have used.

ebruchez
  • 7,760
  • 6
  • 29
  • 41
  • possible duplicate of [What is the best way to limit the amount of text that can be entered into a 'textarea'?](http://stackoverflow.com/questions/378294/what-is-the-best-way-to-limit-the-amount-of-text-that-can-be-entered-into-a-text) – Roddy Jul 29 '11 at 09:28
  • http://stackoverflow.com/questions/378294/what-is-the-best-way-to-limit-the-amount-of-text-that-can-be-entered-into-a-text – personaelit Jan 16 '09 at 20:12

8 Answers8

12

Look at the comments on this site, with a count down. I have done it like this before, and it is simple and effective. Stack Overflow makes good use of color too.

Perhaps you don't have enough rep to see the comment box.

It runs a little countdown while you type. At it approaches a threshold, the color changes from yellow to red. All using JavaScript, and I assume the keyup event of the textarea.

EDIT: How about having it done with jQuery?

<script language="javascript" type="text/javascript" src="js/jquery-1.2.6.min.js"></script>
<script language="javascript" type="text/javascript">
    $(document).ready( function () {
        setMaxLength();
        $("textarea.checkMax").bind("click mouseover keyup change", function(){checkMaxLength(this.id); } )
    });

    function setMaxLength() {
        $("textarea.checkMax").each(function(i){
            intMax = $(this).attr("maxlength");
            $(this).after("<div><span id='"+this.id+"Counter'>"+intMax+"</span> remaining</div>");
        });
    }

    function checkMaxLength(strID){
        intCount = $("#"+strID).val().length;
        intMax = $("#"+strID).attr("maxlength");
        strID = "#"+strID+"Counter";
        $(strID).text(parseInt(intMax) - parseInt(intCount));
        if (intCount < (intMax * .8)) {$(strID).css("color", "#006600"); } //Good
        if (intCount > (intMax * .8)) { $(strID).css("color", "#FF9933"); } //Warning at 80%
        if (intCount > (intMax)) { $(strID).text(0).css("color", "#990000"); } //Over
    }
</script>

And the HTML is

<textarea id="text" maxlength="250" class="checkMax"></textarea>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MrChrister
  • 3,555
  • 5
  • 22
  • 34
  • Be aware: your variables are not explicitly declared with a `var` keyword and, as a result, get injected into the global namespace. This is considered bad practice and can lead to serious issues. – Michael Richardson Mar 16 '14 at 01:45
7

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.

  • 1
    Is it possible to elaborate a bit more on how pasting can be overcome? As far as I know onkeypress will not fire when a user does a right-click to paste text. – Ben Apr 30 '10 at 21:22
  • It's working fine. But as you have mentioned, the user can get around by pasting text.Can that be overcome using 'onchange'? Can you explain? – dev May 09 '14 at 15:38
  • @dev I'm sorry for being cryptic, I don't remember what I was thinking at the time, but 'onchange' sounds right. Also it should be mentioned that no matter what you do on the client side of things, you gotta validate it server-side. – Gissur Þórhallsson May 10 '14 at 10:16
5

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:

<textarea id="text" name="text" maxlength="1250"></textarea>

JS:

function setMaxLength() {
    var x = document.getElementsByTagName('textarea');
    var counter = document.createElement('div');
    counter.className = 'counter';
    for (var i=0;i<x.length;i++) {
        if (x[i].getAttribute('maxlength')) {
            var counterClone = counter.cloneNode(true);
            counterClone.relatedElement = x[i];
            counterClone.innerHTML = '<span>0</span>/'+x[i].getAttribute('maxlength');
            x[i].parentNode.insertBefore(counterClone,x[i].nextSibling);
            x[i].relatedElement = counterClone.getElementsByTagName('span')[0];

            x[i].onkeyup = x[i].onchange = checkMaxLength;
            x[i].onkeyup();
        }
    }
}

function checkMaxLength() {
    var maxLength = this.getAttribute('maxlength');
    var currentLength = this.value.length;
    if (currentLength > maxLength)
        this.relatedElement.className = 'toomuch';
    else
        this.relatedElement.className = '';
    this.relatedElement.firstChild.nodeValue = currentLength;
    // not innerHTML
}

Simply call the setMaxLength(); function on load.

rickyduck
  • 4,030
  • 14
  • 58
  • 93
Zack The Human
  • 8,373
  • 7
  • 39
  • 60
2

Here is JavaScript code that works OK for me:

onBlur="if (this.value.length > 500) { alert('The notes field only allows 500 characters. You have ' + this.value.length + ' characters.'); this.focus(); return false; }"
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sarel Botha
  • 12,419
  • 7
  • 54
  • 59
0

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;
    });
});
richbai90
  • 4,994
  • 4
  • 50
  • 85
0

Here's a jQuery plugin that I use called "Simply Countable" that allows you to add a counter to a textarea. One of the features is that it allows you to set a maximum number of characters that are allowed in a field and it enforces it so the user can't exceed that limit.

Here's the GitHub page for Simply Countable:
https://github.com/aaronrussell/jquery-simply-countable/

You would use it like this...

$('#my_textarea').simplyCountable({
    counter: '#counter',
    maxCount: 140,
    strictMax: true
});
krick
  • 163
  • 1
  • 5
  • 17
0

I think the following is as "clean" as it gets. Make an event handler in Javascript that takes the keydown event and the textarea field as input. Check the length of the text in the field in this handler and return false if the maxlength is reached. (Of course make any css style switching before returning). Return true otherwise. The textarea should look like this.

<textarea onkeydown="return checkMaxLength(event, this, 1000);"></textarea>
PEZ
  • 16,821
  • 7
  • 45
  • 66
0

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jay Prall
  • 5,295
  • 5
  • 49
  • 79