Often we need to set maxlength property to textarea. But problem is, it is not working in textarea. It works fine to TextBox. Then how to solve this similar to textbox control.
Code example are given bellow
var control = $("[id$='txtPairTitle']");
$(document).ready(function() {
$(control).keypress(function(event) {
var e = event || window.event;
var keyCode = e.which || e.keyCode;
//46 delete; 8 backspace; 37 left arrow, 39 right arrow; 39 top; 40 bottom
if (keyCode == 46 || keyCode == 8 || keyCode == 37 || keyCode == 39 || keyCode == 38 || keyCode == 40)
return true;
var isExit = isExitMaxLength(140);
if (isExit) {
event.returnValue = false;
}
return !isExit;
});
});
function isExitMaxLength(maxLength) {
var length = control.val().length;
return length > maxLength;
}
function maxLengthPaste(maxChars) {
window.setTimeout(function() {
if (window.event)
window.event.returnValue = false;
data = control.val();
if ((data.length > maxChars)) {
control.val('');
alert("more than " + maxChars + " chars");
return false;
}
if (window.event)
window.event.returnValue = true;
}, 10);
}
Note: OnPaste event not work in safari. So you can search some jquery plugin to handle that issue.