Reputation: 10448
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
Upvotes: 0
Views: 6622
Reputation: 5493
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);
});
});
Upvotes: 1
Reputation: 366
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);"
Upvotes: 0
Reputation: 413717
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.
Upvotes: 1
Reputation: 1000
Take a look at this: How to impose maxlength on textArea in HTML using JavaScript
Upvotes: 2