Here is a solution using javascript which helps to restrict the
number of letters which can be entered in a html textarea field. Effectively providing the textarea field with a max length property.
<script type="text/javascript" language="javascript">
function CheckMaxLength( txt, size, error)
{
error = document.getElementById( error);
if( txt.value.length >= size)
{
error.style.display = "";
if(txt.value.length > size)
txt.value = txt.value.substr( 0, size);
return;
}
error.style.display = "none";
}
</script>
<textarea id="f" rows="4" cols="20" onkeyup="CheckMaxLength( this, 10, 'error_message');" >
</textarea>
<span style="display:none;" id="error_message"> The textarea is full!</span>
Here we declare a function CheckMaxLength() which takes 3 parameters.
First is the textarea which to check, second is the maximum size allowed and the third is the id of the element which contains the message to display.
In the html markup, we have a textarea who's onkeyup contains a call to the CheckMaxLength() function providing the required arguments.
We also have a hidden span with the error message which we want to display to the user when the textarea reaches its maximum length.
We should be providing the id of this element as the third parameter to the CheckMaxLength() function.
The code inside the function simply checks if the length of the text in the textarea is greater or equals to the size provided.
If so, it sets the element's display style property to "" containing the error message making it visible. and set the text of the textarea
after taking the first size characters. This method stops users from pasting large text into the textarea as the onkeyup event will be triggered while pasting and the size will be checked.
The function then sets the display style property of the error message element to "none" hiding it if the length doesn't exceeds the provided size.
You can modify the script and its action according to your needs and make it a useful and perfect snippet to meet your circumstance.
Happy hacking!