0

Im using Html.TextArea in my application and when i set its maxlength property to 255. It doesnt work and write more than 255 characters. how can this problem be solved

Fraz Sundal
  • 10,288
  • 22
  • 81
  • 132

4 Answers4

2

Take a look at this: How to impose maxlength on textArea in HTML using JavaScript

Community
  • 1
  • 1
Tor-Erik
  • 990
  • 8
  • 25
1

The HTML <textarea> tag does not support the "maxlength" property. A variety of Javascript solutions exist, some for frameworks and others stand-alone. Basically it's necessary to catch keypress events (with Javascript) and track the content length. Usually some messaging to users is considered a Really Good Idea, like the Stackoverflow "Comment" boxes have.

Pointy
  • 405,095
  • 59
  • 585
  • 614
1

This will prevent longer text being entered or pasted into any text areas. All you need to do is add the 'maxlength' attribute.

$(function () {
    //This bit will prevent the user from typing in too many characters...
    $('textarea').keypress(function (e) {
        //TODO: error handling...
        var limit = parseInt($(this).attr('maxlength'));
        var currentText = $(this).val();
        var chars = currentText.length;

        //too many charaters?
        if (chars >= limit) {
            e.preventDefault(); //cancel the key press
        }
    });

    //This bit will prevent the user pasting in long strings...
    $('textarea').bind('paste', function () {
        //TODO: error checking
        var limit = parseInt($(this).attr('maxlength'));
        var element = $(this);
        setTimeout(function () {
            var currentText = element.val();            
            var chars = currentText.length;
            if (chars > limit) {                
                //get the first 'n' characters
                var newText = currentText.substr(0, limit);
                //and replace the text.
                element.val(newText);
            }
        }, 10);
    });
});
Community
  • 1
  • 1
Simon
  • 5,373
  • 1
  • 34
  • 46
0

You can use a JavaScript validator. For example,

    function limitText(limitField, limitCount, limitNum) {
        if (limitField.value.length > limitNum) {
            limitField.value = limitField.value.substring(0, limitNum);
        } else {
            limitCount.value = limitNum - limitField.value.length;
        }
    }
<textarea name="limitedtextarea" onKeyDown="limitText(this.form.limitedtextarea,this.form.countdown,255);" 
SageNS
  • 356
  • 2
  • 5