Introduction
If you are using textbox, then you have the freedom to restrict the amount of data that a user can enter by using MaxLength
attribute.
But if you are using a textarea, then there is no default support for this.
In this tip, I will discuss how to create a textarea plugin in jQuery which will serve the purpose.
Background
HTML Textarea does not provide any default support for the maximum length that can be entered into it. So to achieve this, I am going to write a jQuery plugin.
Pages
- One HTML Page
- jQuery library file
- Below jQuery
TruncateLength
plugin.
Using the Code
(function($){
$.fn.truncateLength = function(options) {
var defaults = {
fontSize: 10,
backColor: '#FAFAB2',
foreColor: '#FF0000',
fadeinTime: 500,
fadeoutTime: 1500,
maxLength: 100,
overrideStyle: false,
cssClass: ''
};
var opt = $.extend(defaults, options);
return this.each(function() {
var me = $(this);
if(me.is('textarea')) {
me.keyup(truncateText);
var maxLength = parseInt(opt.maxLength);
function truncateText(e) {
if(!isNaN(maxLength) && me.val().length > maxLength) {
var cell = {
Height: me[0].offsetHeight,
Width: me[0].offsetWidth,
Top: me.offset().top,
Left: me.offset().left
};
var truncatedText = me.val().substring(0, maxLength);
var popup = $('<p />').html('Max limit reached (' + maxLength + ' chars).')
.css({
'top': cell.Top + 'px', 'left': cell.Left + 'px',
'height': cell.Height + 'px', 'width': cell.Width + 'px',
'position': 'absolute', 'display': 'none'
});
if(opt.overrideStyle && opt.cssClass) {
popup.addClass(opt.cssClass);
} else {
popup.css({
'background-color': opt.backColor, 'color': opt.foreColor,
'font-size': opt.fontSize + 'px', 'text-align': 'center',
'line-height': cell.Height + 'px', 'z-index': '1001'
});
}
me.val(truncatedText).css('z-index', '1').after(popup).blur();
popup.fadeIn(opt.fadeinTime, function()
{
me.focus();
$(this).fadeOut(opt.fadeoutTime, function()
{
$(this).remove();
});
});
}
};
}
});
};
})(jQuery);
Add this in a js file and include this in the page where you require it.
Now to use it, we will write:
$('#txtComment').truncateLength({ maxLength: 10 });
Sample HTML Page's Content:
<head>
<script src="js/jquery-1.3.2.js"></script>
<script src="js/TruncateLength.js"></script>
<script type="text/javascript">
$(function () {
$('#txtComment').truncateLength({ maxLength: 10 });
});
</script>
</head>
<body>
<textarea id="txtComment"></textarea>
</body>
Live Demo
Points of Interest
It is very easy to create such a plugin but is very usable.
This plugin had helped me a lot and I know it will help you too.
History