25

I am trying to limit the number of characters entered in a textarea as shown:

<div>
 @Html.TextAreaFor(x => x.StudentName, new { @maxlength = "1000" })
</div>

This works fine in Firefox and Chrome but the maxlength attribute doesn't work in IE. How do I do that??

Infant Dev
  • 1,659
  • 8
  • 24
  • 48
  • 1
    See http://stackoverflow.com/questions/1125482/how-to-impose-maxlength-on-textarea-in-html-using-javascript – Tim M. Feb 02 '12 at 08:44
  • @TimMedora: So why not mark the question as a duplicate? – leppie Feb 02 '12 at 08:46
  • 1
    @leppie - because last time I searched for a maxlength script that worked in all cases, I ended up writing my own. The post I linked to is over 18 months old; there may be a better solution out there but I figured it would give the OP somewhere to start at least. Just my opinion. – Tim M. Feb 02 '12 at 08:49

4 Answers4

17

The maxlength attribute is not standard for <textarea> in HTML 4.01. It is defined in HTML5 though but I guess IE doesn't implement it. To make it work across all browsers you could use javascript. Here's an example.

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
12

Here is my jQuery based solution. Works well in IE9, a little wonky in IE8.

// textarea event handler to add support for maxlength attribute
$(document).on('input keyup', 'textarea[maxlength]', function(e) {
    // maxlength attribute does not in IE prior to IE10
    // http://stackoverflow.com/q/4717168/740639
    var $this = $(this);
    var maxlength = $this.attr('maxlength');
    if (!!maxlength) {
        var text = $this.val();

        if (text.length > maxlength) {
            // truncate excess text (in the case of a paste)
            $this.val(text.substring(0,maxlength));
            e.preventDefault();
        }

    }

});

http://jsfiddle.net/hjPPn/

link for IE8: http://jsfiddle.net/hjPPn/show

Native Browser Support

Also, in case you're wondering which browsers do support maxlength: https://caniuse.com/#search=maxlength

Walter Stabosz
  • 7,447
  • 5
  • 43
  • 75
3

You can use javascript as well, which is way easier:

<textarea  name="question" cols="100" rows="8" maxlength="500px" onKeyPress="return ( this.value.length < 1000 );"></textarea>
erdomester
  • 11,789
  • 32
  • 132
  • 234
1

Use the following Jquery - for eg, if you want to restrict the length to 48

$("textarea").keypress(function(e){
    var lengthF = $(this).val();

    if (lengthF.length > 48){
        e.preventDefault();
    }
});