简体   繁体   中英

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

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.

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>

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.

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.

这是适用于我的JavaScript代码:

onBlur="if (this.value.length > 500) { alert('The notes field only allows 500 characters. You have ' + this.value.length + ' characters.'); this.focus(); return false; }"

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;
    });
});

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
});

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM