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. function max(txarea)
  2. {
  3. total = 240;
  4. tam = txarea.value.length;
  5. str="";
  6. str=str+tam;
  7. document.getElementById("digitado").innerHTML = str;
  8. document.getElementById("restante").innerHTML = total - str;
  9. if (tam > total){
  10. aux = txarea.value;
  11. txarea.value = aux.substring(0,total);
  12. document.getElementById("digitado").innerHTML = total;
  13. document.getElementById("restante").innerHTML = 0;
  14. }
  15. }

Salve o c贸digo abaixo como exemplo.html

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  5. <title>Exemplo</title>
  6. <script type="text/javascript" src="textarea.js"></script>
  7. </head><body><label>Texto:<br /><textarea name="texto" cols="55" rows="4" onkeyup="max(this)" onkeypress="max(this)"><? echo $texto; ?></textarea></label><br />
  8. Caracteres digitados: <font id="digitado" style="color:red; font-weight:bold;">0</font> &nbsp; / &nbsp; Restanges: <font id="restante" style="color:red; font-weight:bold;">240</font><br /><br /></body>
  9. </html>

Fa莽a meu trabalho valer a pena e comente se utilizar.
have fun!