Reputation: 13788
Is there a canonical solution for limiting the number of characters that someone can enter into a textarea?
I have server side validation of course, but would like to improve the user experience by adding client side code to simulate the experience you get with maxlength on an input[type="text"] so that users never see the "your input is too long" error message if they have javascript enabled.
Upvotes: 7
Views: 1003
Reputation: 25157
Attach an onchange event to the textarea. There you can check if the value's larger than the appropriate or not. Example with jQuery:
$("#textarea-id").change(function (){
var text = $(this).val();
if( text.length > MAX ){
return false;
}
});
Upvotes: 1
Reputation: 82523
This will do it...
function textareaMaxLen(event) {
var max = parseInt(this.attr("maxlength"), 10);
if(this.value.length >= max)
this.value = this.value.substr(0, max);
}
$("textarea").keyup(textareaMaxLen).blur(textareaMaxLen);
Upvotes: 1
Reputation: 10102
I would do it this way:
$ ('#textarea-id').bind (
'change input keyup keydown keypress mouseup mousedown cut copy paste',
function () { return ($(this).val().length <= maxlength) }
)
So many bingings just to be completely sure :-)
Upvotes: 5
Reputation: 43875
My non-technical $0.02
Do what SO does in their comment fields, provide feedback as to what the user's character length remaining is and allow them to go past the maximum, but not submit > 300 characters. Here's why:
Upvotes: 23
Reputation: 14906
I've done it like this in the past:
<textarea onkeyup="checkLength(this);"></textarea>
Then implement this function:
function checkLength(control) {
if (control.value.length > 5) {
control.value = control.value.substr(0, 5);
}
}
It's a pretty basic example fixing the length to 5, but hopefully gives you the idea!
Upvotes: 0