Maxlength for text area doesn't work in IE

2019-01-25 02:38发布

问题:

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??

回答1:

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.



回答2:

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



回答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>


回答4:

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