Setting maxlength to a textarea
The maxlength attribute is new for the <textarea> tag in HTML5.
But what if you are not using html5 or what if your browser doesn't support this attribute.
You might have faced this issue where you being not able to set maxlength property to a textarea.But what if you are not using html5 or what if your browser doesn't support this attribute.
So here is the trick using the power of Jquery :P.
var maxLength = 50; //Set the length hereExplanation:
$(document).ready(function(){
setMaxLenTexrArea();
});
function setMaxLenTexrArea() {
$("textarea").each(function () {
$(this).on('change keydown keyup keypress paste blur', function () {
restrictLength($(this).prop('id'));
});
});
}
function restrictLength(ta) {
var txtVal = $("#" + ta).val();
if (txtVal.length > maxLength) {
txtVal = txtVal.substring(0, maxLength);
$("#" + ta).val(txtVal);
}
}
- maxLength variable will hold the length.
- On document load we will be calling setMaxLenTexrArea() method.
- We will be restricting the user to enter (type/paste) only allowed number of characters by checking the existing values length in the textarea and not allowing further if it has reached thr limit.
Comments
Post a Comment