19 de abril de 2007Limitando caracteres em uma textarea
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
- 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
- <!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!


Excelente post, pratico e rapido.
Parab茅ns.
[Responder]
Parab茅ns, muito pr谩tico mesmo.
[Responder]