For a textbox, character of a field can easily be limited with maxlength attribute. But maxlength doesn’t work for a textarea. So, It needs an alternate way. For one of my project, I wrote a function for this purpose where I used jQuery. Here I am explaining how I did it.
Let’s look an example of this interactive solution here.
OK. Now we will make this in 2 easy steps.
1. Import your jQuery file and write the function "limitChars(textid, limit, infodiv)" in the head section of your page.
This function takes 3 parameters. They are:
- textid : (string) The ID of your textarea.
- limit : (num) The number of character you allow to write.
- infodiv : (string) The ID of a div, in which limit information will be shown .
Here is the function:
1: <script language="javascript" src="Jquery.js"></script>
2: <script language="javascript">
3: function limitChars(textid, limit, infodiv)
4: {
5: var text = $('#'+textid).val();
6: var textlength = text.length;
7: if(textlength > limit)
8: {
9: $('#' + infodiv).html('You cannot write more then '+limit+' characters!');
10: $('#'+textid).val(text.substr(0,limit));
11: return false;
12: }
13: else
14: {
15: $('#' + infodiv).html('You have '+ (limit - textlength) +' characters left.');
16: return true;
17: }
18: }
19: </script>
1: $(function(){
2: $('#comment').keyup(function(){
3: limitChars('comment', 20, 'charlimitinfo');
4: })
5: });
1: function limitChars(textarea, limit, infodiv)
2: {
3: var text = textarea.value;
4: var textlength = text.length;
5: var info = document.getElementById(infodiv);
6:
7: if(textlength > limit)
8: {
9: info.innerHTML = 'You cannot write more then '+limit+' characters!';
10: textarea.value = text.substr(0,limit);
11: return false;
12: }
13: else
14: {
15: info.innerHTML = 'You have '+ (limit - textlength) +' characters left.';
16: return true;
17: }
18: }
1: <textarea name="comment" id="comment" onkeyup="limitChars(this, 20, 'charlimitinfo')">
2: </textarea>
Please let me know if you have an idea to make it better.