Bom, em um dos meus projetos surgiu a necessidade de limitar caracteres digitados em uma textarea, buscando no meu guru encontrei muitas coisas a respeito, porem antigas e não funcionais em alguns browsers. Depois de pegar um código aqui, remendar aqui e acula, o resultado foi bacana. O script roda em todos* os browsers sem erro algum.
Salve o codigo abaixo em um arquivo com o nome textarea.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | function max(txarea) { total = 240; tam = txarea.value.length; str=""; str=str+tam; document.getElementById("digitado").innerHTML = str; document.getElementById("restante").innerHTML = total - str; if (tam > total){ aux = txarea.value; txarea.value = aux.substring(0,total); document.getElementById("digitado").innerHTML = total; document.getElementById("restante").innerHTML = 0; } } |
Salve o código abaixo como exemplo.html
1 2 3 4 5 6 7 8 9 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Exemplo</title> <script type="text/javascript" src="textarea.js"></script> </head><body><label>Texto:<br /><textarea name="texto" cols="55" rows="4" onkeyup="max(this)" onkeypress="max(this)"><? echo $texto; ?></textarea></label><br /> Caracteres digitados: <font id="digitado" style="color:red; font-weight:bold;">0</font> / Restanges: <font id="restante" style="color:red; font-weight:bold;">240</font><br /><br /></body> </html> |
Faça meu trabalho valer a pena e comente se utilizar.
have fun!

novembro 26th, 2007 at 22:41
Excelente post, pratico e rapido.
Parabéns.
dezembro 17th, 2007 at 17:29
Parabéns, muito prático mesmo.
fevereiro 25th, 2010 at 19:27
Olá,
Parabéns! Muito bom!!! :)
Já estava desistindo de encontrar um limitador de textarea
Obrigada!