Ir para conteúdo

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

inhokinformatica

Formatar um <textarea> com javascript

Recommended Posts

Bom dia pessoal, tudo bem?

 

O negócio é o seguinte. Na empresa onde trabalho utilizamos uma máscara pra abrir chamados em um sistema DOS em que cada linha suporta 30 caracteres. Para agilizar, estou tentando desenvolver uma página simples em HTML + Javascript para formatar um <textarea> em que ele quebre a linha com 30 caracteres. Como não manjo muito de javascript e não posso instalar o apache para rodar arquivos php devido a restrição nas máquinas, quem pudesse me ajudar ficaria muito agradecido. Pesquisando no google encontrei essa função:

 

<script language="javascript">
/*----------------------------------------------------------------------------
Formatação para qualquer mascara
-----------------------------------------------------------------------------*/
function formatar(src, mask){
  var i = src.value.length;
  var saida = mask.substring(0,1);
  var texto = mask.substring(i)
if (texto.substring(0,1) != saida)
  {
    src.value += texto.substring(0,1);
  }
}
</script>

Para formatar o campo do formulário, ficaria da seguinte forma.

<textarea rows="5" cols="30" OnKeyPress="formatar(this, '#############################\n#############################\n#############################\n############################')">

Pois bem. Encontrei diversas formas para armazenar uma variável javascript e independente delas, não consigo formatar a quebra de linha.

 

Essa é página index.html:

 

<script type="text/javascript">
function setCookie(cookie_name, cookie_value, expire_in_days)
{
var cookie_expire = "";

  if (expire_in_days != null)
  {
	var expire = new Date();
	expire.setTime(expire.getTime() + 1000*60*60*24*parseInt(expire_in_days));
	cookie_expire = "; expires=" + expire.toGMTString();
  }

 document.cookie = escape(cookie_name) + "=" + escape(cookie_value) + cookie_expire;
}

function getCookie(cookie_name)
{
  if (!document.cookie.match(eval("/" + escape(cookie_name) + "=/")))
  {
   return false;
  }

return unescape(document.cookie.replace(eval("/^.*?" + escape(cookie_name) + "=([^\\s;]*).*$/"), "$1"));
}


// Acessando
function LeCookie()
{
cookie = getCookie("nome");

if (!cookie)
 document.getElementById("resultado_cookie").innerHTML = "Fomulário não gerado";
else
 document.getElementById("resultado_cookie").innerHTML = cookie;
}
</script>
<table border="0">
<tr>
<td>Usuario:</td>
<td><input type="text" name="nome" id="nome"></td>
</tr>

<tr>
<td>Grupo:</td>
<td>
<select name="grupo" id="grupo">
  <option value="administrativo">Administrativo</option>
  <option value="financeiro">Financeiro</option>
  <option value="manutencao">Manutenção</option>
</select>
</td>
</tr>

<tr>
<td>Problema:</td>
<td>
<select name="defeito" id="defeito">
  <option value="computador">Computador</option>
  <option value="internet">Internet</option>
  <option value="sistema">Defeito</option>
</select>
</td>
</tr>

<tr>
<td><input type="button" value="Gravar" onclick="setCookie('nome', '<textarea rows=5 cols=30>Usuario:'+document.getElementById('nome').value+',Grupo:'+document.getElementById('grupo').value+',Problema  '+document.getElementById('defeito').value+'</textarea>', 1)"></td>
<td><input type="button" value="Gerar Formuário" onclick="LeCookie()"></td>
</tr>

</table>
<br>
<div id="resultado_cookie"></div>

Tentei colocar

<input type="button" value="Gravar" onclick="setCookie('nome', '<textarea rows=5 cols=30 OnKeyPress=formatar(this, '#############################\n#############################\n#############################\n############################')>Usuario:'+document.getElementById('nome').value+',Grupo:'+document.getElementById('grupo').value+',Problema  '+document.getElementById('defeito').value+'</textarea>', 1)">

Alguém me dá uma luz?

Compartilhar este post


Link para o post
Compartilhar em outros sites

Esse é o problema, não sei como fazer isso. Se eu tento utilizar a função formatar, ela não funciona.

 

Acho que teria que contar os caracteres do

 

document.getElementById("resultado_cookie").innerHTML = cookie;

e a cada 30 caracteres inserir um \n ou <br> mas como fazer isso em javascript?

 

Teria alguma função while?

Compartilhar este post


Link para o post
Compartilhar em outros sites

Cara, eu fiz um gato aqui que funcionou rs
Não sei se seria a forma mais correta .. Tente melhorar o código.

 

 

<!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=utf-8" />
<title>Documento sem título</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(function(){
 
 
var string= $("#quebra").val();
var primeiraLinha = string.substring(0,30);
var segundaLinha = string.substring(31,61);
var terceiraLinha = string.substring(62,92);
var quartaLinha = string.substring(93,126);
$("#quebra").val(
primeiraLinha+"\n"+
segundaLinha+"\n"+
terceiraLinha+"\n"+
quartaLinha+"\n");
 
});
</script>
<style>
textarea {
width:600px;
height:300px;
text-align:left !important;
resize:none;
}
 
</style>
</head>
 
<body>
<textarea id="quebra">Lorem Ipsum is simply dummy text of the printing and 
typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an 
unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five 
centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s 
with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop 
publishing software like Aldus PageMaker including versions of Lorem Ipsum.</textarea>
<br /><br />
<b>SEM QUEBRA</b><br />
<textarea>Lorem Ipsum is simply dummy text of the printing and 
typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an 
unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five 
centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s 
with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop 
publishing software like Aldus PageMaker including versions of Lorem Ipsum.</textarea>
</body>
</html>
 

Compartilhar este post


Link para o post
Compartilhar em outros sites


<html>

<head>

<title>jt</title>

<script>

window.onload = function(){

 

var s = document.getElementById('quebra').value.replace(/\n/g, '' ),t='';

var c = 30,cr = 30;

 

 

for(var x = 0; x<=s.length -1; x++){

 

t += s[x];

if(x == c -1){

t+= '\n';

c = c + cr;

}

}

 

document.getElementById('quebra').value = t;

}

</script>

<style>

textarea {

width:600px;

height:300px;

resize:none;

}

 

</style>

</head>

 

<body>

<textarea id="quebra">Lorem Ipsum is simply dummy text of the printing and

typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an

unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five

centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s

with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop

publishing software like Aldus PageMaker including versions of Lorem Ipsum.</textarea>

 

 

</body>

</html>

Compartilhar este post


Link para o post
Compartilhar em outros sites

outro exemplo seria assim:


<html>
<head>
<title>oO</title>
<script>
window.onload = function(){
var oldValue = document.getElementById('quebra').value;
var newValue = oldValue.replace(/\n/g,'').split(/(.{30})/g).filter(function(v){ return (v != '')}).join('\n');
document.getElementById('quebra').value = newValue;
}
</script>
</head>

<body>
<textarea id="quebra" cols="45" rows="25">Lorem Ipsum is simply dummy text of the printing and 
typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an 
unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five 
centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s 
with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop 
publishing software like Aldus PageMaker including versions of Lorem Ipsum.</textarea>
</body>
</html>

 

espero que tambem ajude, abraço!

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.