Advanced maxlength JavaScript
function getlength(id)
{
return document.getElementById(id).value.length;
}
function getcurrenttxt(id, max)
{
if(getlength(id) >= max)
return document.getElementById(id).value.substr(0, max);
}
function usertyping(id, max, notice)
{
var ID = document.getElementById(id);
var Notice = document.getElementById(notice);
if(ID && Notice)
{
Notice.innerHTML = '<span>' + (getlength(id) == (max+1) ? max : getlength(id)) + '</span>/' + max;
if(getlength(id) >= max) {
ID.value = getcurrenttxt(id, max);
}
}
}
What this does is, it checks the character length in a textarea (or whatever you want), and if that length exceeds max, it won’t let the user type anymore (it actually does something else, but that’s the effect). Also, it lists the character limit of the textarea that specify and also the max. It’s fairly simple to just list the amount the user has left,
function usertyping(id, max, notice)
{
var ID = document.getElementById(id);
var Notice = document.getElementById(notice);
if(ID && Notice)
{
Notice.innerHTML = '' + (max - getlength(id)) + '';
if(getlength(id) >= max) {
ID.value = getcurrenttxt(id, max);
}
}
}
Of course, I prefer the first method.
If you like the script to onload (load when the page does), then here’s a function I wrote just for that:
function body_onload()
{
var limits = new Array();
limits[0] = new Array('bm_text', 255, 'char_limit');
for(var i = 0; i < limits.length; i++)
usertyping(limits[i][0], limits[i][1], limits[i][2]);
}
Just list the textareas and the information in the limits array, and then call it when the body loads. Of course, even if the specified textareas don’t exist, it won’t cause trouble - the script checks if the appropriate elements exist before doing anything.
If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!