John Smith
John Smith

Reputation: 851

how to make textarea inactive with jQuery

i have such html code and i'm using jQuery:

<div><textarea style="height: 150px; width: 250px" name="myName" id="myId" class="text ui-widget-content ui-corner-all" > </textarea></div>

as for now, i validate this field after submit button is pressed. but how can I inactivate it while typing symbols? f.e. max amount is 50 symbols and on the 51 symbol it becomes inactive or it in any way disallows user's typing, so the user cannot type more than 50 symbols. how to implement it with jQuery? thnx.

Upvotes: 3

Views: 290

Answers (3)

Blazemonger
Blazemonger

Reputation: 92893

Monitor the textarea, and whenever a key is pressed, trim the length of its contents:

$('textarea').on('keyup',function(e) {
    var clen = 50,
        $this = $(this);
    if ($this.val().length > clen) {
        $this.val($this.val().substr(0,clen));
    };
});

http://jsfiddle.net/mblase75/AYUeE/

Since the maxlength attribute was only added to textareas in HTML5, you should use a JavaScript-based solution like this in addition to that for maximum reliability.

Upvotes: 1

bfavaretto
bfavaretto

Reputation: 71908

No jQuery needed, add the maxlength attribute:

<textarea maxlength="50"></textarea>

Upvotes: 2

bpeterson76
bpeterson76

Reputation: 12870

Use Limit

$('#myId').limit('50,'#charsLeft');

Upvotes: 0

Related Questions