Ir para conteúdo

Arquivado

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

Rodrigo5468

Gerar Texto

Recommended Posts

Bom dia.

Eu tenho um HTML com vários input e textarea. Eu queria fazer um botão chamado código, que quando clica-se no botão iria pegar o texto do input e da textarea e colocar em um formato. Exemplo:

Input 1

Bem vindo ao Input 1

Textarea 1

Descrição do Textarea 1

Aí iria gerar um formato e colocar ele dentro de uma textarea chamado resultado. Ao clicar em Gerar Código.

<h2>Bem vindo ao Input 1</h2>
<span style="color:red;">Descrição do Textarea 1>

Como que eu posso fazer isso em jQuery?

Obrigado.

Compartilhar este post


Link para o post
Compartilhar em outros sites

<meta charset="utf-8">

<input type="text" id="title" value="Bem vindo ao Input 1">

<textarea id="description">Descrição do Textarea 1</textarea>

<textarea id="result" cols="50" rows="10"></textarea>

<script type="text/javascript">

var $title = document.getElementById('title'),

$description = document.getElementById('description'),

$result = document.getElementById('result');

$result.value = '<h2>' + $title.value + '</h2>\n' +

'<span style="color:red;">' + $title.value + '</span>';

</script>

Compartilhar este post


Link para o post
Compartilhar em outros sites

Muito obrigado.

Eu gostaria de fazer uma função na descrição. Queria colocar um botão com a função de "Adicionar" e "Remover", esses botões iriam adicionar e remover as descrições. E com um numerador, irei deixar uma print de como eu gostaria que fica-se.

PADRÃO - SEM ADICIONAR

p716Ua9.png

ADICIONAR ATIVO e COM OPÇÃO DE ADICIONAR E REMOVER

bJCv6qC.png

Poderia me ensinar como posso fazer essa função?

Compartilhar este post


Link para o post
Compartilhar em outros sites

no click do botão você dá um appendChild ou um .innerHTML do html desse input novo.

existem exemplos prontos disso na internet, dá uma pesquisada =)

Compartilhar este post


Link para o post
Compartilhar em outros sites

William tentei assim, mas não obtive resultado.

jQuery(document).ready(function(){
	jQuery("#textshow").click(function(){
		jQuery("#textshow").after('<textarea></textarea>');
		
		jQuery("#textshow").hide();
		jQuery("#texthide").show();
	});
	
	jQuery("#texthide").click(function(){
		jQuery("#texthide").hide();
		jQuery("#textshow").show();
		jQuery("#textaviso").remove();
	});
});

O quê devo fazer? Onde estou errando?

Obrigado desde já.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Exemplo:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
<style type="text/css">
body { background: #F4F6F7; }
label, b { display: block; }
</style>
</head>
<body>

<label>
  <b>Título</b>
  <input type="" name="" />
</label>

<label>
  <b>1 Descrição</b>
  <textarea></textarea>
</label>

<div id="target"></div>


<button type="button" id="add">Adicionar</button>
<button type="button" id="rm">Remover</button>


<script src="jquery.min.js"></script>
<script>
var qnt = 1;
var $target = $('#target');
$('#add').on('click', function() {
  $target.append('<label><b>' + (++qnt) + ' Descrição</b><textarea></textarea></label>');
});
$('#rm').on('click', function() {
  --qnt;
  $target.find('label:last-child').remove();
});

</script>

</body>
</html>

Compartilhar este post


Link para o post
Compartilhar em outros sites

Funcionou, adaptei para meu código e deu tudo certo.

Porem há um problema, o problema é o seguinte William. Quando eu clico em Remover, ele remove mas, ao ficar clicando ele vai adicionar -. Deixando 0, -1, -2 e assim por diante. Eu gostaria que remove-se até o número 1 e deixar sempre o um, e ao adicionar ir adicionando. E remover até o 1. Como posso fazer isso?

Tentei tirar o -- mais sem sucesso. (--qnt;)

Compartilhar este post


Link para o post
Compartilhar em outros sites

é um if cara.. testa se o qnt é maior que 1, se não for, você não remove.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Desculpa qualquer coisa William. Conseguir resolver o problema, como dito fiz o IF.

Mas tem um problema, como posso arruma-lo? Se clicar em adicionar os novos itens adicionados não são gerados.

<html>
	<head>
		<meta charset="UTF-8"/>
		<title>Gerador</title>
		<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
		<style type="text/css">
			body {
				background: #F4F6F7;
			}
			label, b {
				display: block;
			}
		</style>
	</head>
	
	<body>
		<label>
			<b>Título</b>
			<input type="text" name="title" id="title"/>
		</label>
		
		<label>
			<b>1 Descrição</b>
			<textarea  name="description" id="description"></textarea>
		</label>
		
		<div id="target"></div>
		
		<button type="button" id="add">Adicionar</button>
		<button type="button" id="rm">Remover</button>
		
		<br/><br/><br/><br/>
		
		<input type="submit" value="Gerar" onclick="funcgerar();"/>
		
		<br/><br/><br/><br/>
		
		<textarea  name="result" id="result" style="margin: 0px; width: 453px; height: 215px;"></textarea>
		
		<script>
		var qnt		= 1;
		var $target = $('#target');
		
		$('#add').on('click', function(){
			$target.append('<label><b>' + (++qnt) + ' Descrição</b><textarea  name="description" id="description"></textarea></label>');
		});
		$('#rm').on('click', function(){
			if(qnt==1) return 1;
			--qnt;
			$target.find('label:last-child').remove();
		});
		
		function funcgerar(){
			var $title = document.getElementById('title'),
				$description = document.getElementById('description'),
				$result = document.getElementById('result');
				
				$result.value = '<h2>' + $title.value + '</h2>\n' + '<span style="color:red;">' + $description.value + '</span>';
		}
		</script>
	</body>
</html>

O que devo fazer? Obrigado por tudo.

Compartilhar este post


Link para o post
Compartilhar em outros sites

porque ai você precisa de um loop

<html>
  <head>
    <meta charset="UTF-8"/>
    <title>Gerador</title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
    <style type="text/css">
      body {
        background: #F4F6F7;
      }
      label, b {
        display: block;
      }
    </style>
  </head>

  <body>
    <label>
      <b>Título</b>
      <input type="text" name="title" id="title"/>
    </label>

    <label>
      <b>1 Descrição</b>
      <textarea name="description"></textarea>
    </label>

    <div id="target"></div>

    <button type="button" id="add">Adicionar</button>
    <button type="button" id="rm">Remover</button>

    <br/><br/><br/><br/>

    <input type="submit" value="Gerar" onclick="funcgerar();"/>

    <br/><br/><br/><br/>

    <textarea name="result" id="result" style="margin: 0px; width: 453px; height: 215px;"></textarea>

    <script>
    var qnt   = 1;
    var $target = $('#target');

    $('#add').on('click', function(){
      $target.append('<label><b>' + (++qnt) + ' Descrição</b><textarea name="description"></textarea></label>');
    });
    $('#rm').on('click', function(){
      if(qnt==1) return 1;
      --qnt;
      $target.find('label:last-child').remove();
    });

    function funcgerar(){
      var $title = document.getElementById('title'),
        $descriptions = document.querySelectorAll('textarea[name="description"]'),
        $result = document.getElementById('result');

        $result.value = '<h2>' + $title.value + '</h2>\n';

        $descriptions.forEach(function($desc) {
          $result.value += '<span style="color:red;">' + $desc.value + '</span>\n';
        });
    }
    </script>
  </body>
</html>

Compartilhar este post


Link para o post
Compartilhar em outros sites

Obrigado William, só tenho uma dúvida no funcionamento do código.

$descriptions = document.querySelectorAll('textarea[name="description"]'),

Se eu quiser adicionar novos itens com nomes diferentes o quê devo fazer para funcionar ao clicar em Gerar?

Mais uma vez, obrigado!

Compartilhar este post


Link para o post
Compartilhar em outros sites

Se forem itens adicionados dinamicamente, você tem que colocar mais loops

se forem apenas um item igual o title, basta concatenar.

Compartilhar este post


Link para o post
Compartilhar em outros sites

William fiz como você pediu e está funcionando perfeitamente. Porem há um problema, como posso arrumar este pequeno problema?

<html>
	<head>
		<title>Gerador de Guias e Tutoriais</title>
		<meta charset="UTF-8"/>
		<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
		
		<style type="text/css">
			fieldset dd input, fieldset dd textarea {
				margin-left: 5%;
			}
			.gerar {
				;
				margin-top: 5%;
			}
		</style>
	</head>
	
	<body>
		<fieldset class="fields1">
			<dl>
				<dt>
					<label>Título:</label>
				</dt>
				
				<dd>
					<input type="text" name="title" id="title" required="required" size="25" tabindex="1" class="inputbox autowidth" style="clear: both; width: 510px;" value=""/>
				</dd>
			</dl>
			
			<dl id="warningtext">
				<dt>
					<label>Descrição:</label>
				</dt>
				
				<dd>
					<textarea name="descricao" id="descricao" tabindex="4" class="inputbox" style="clear: both; height: 100px; width:510px;"></textarea>
				</dd>
			</dl>
			
			<dl>
				<dd>
					<input type="button" id="warningshow" value="Adicionar aviso" class="button2"/>
					
					<input type="button" id="warninghide" value="Remover aviso" class="button2" style="display:none;"/>
				</dd>
			</dl>
			
			<dl id="passo">
				<dt>
					<label>1º -</label>
				</dt>
				
				<dd>
					<input type="text" name="titulopasso" id="titulopasso" placeholder="Título" size="25" tabindex="1" class="inputbox autowidth" style="clear:both;width:510px;color:darkblue;font-weight:bold" value=""/>
					
					<br/><br/>
					
					<textarea name="descricaopasso" id="descricaopasso" placeholder="Descrição" tabindex="4" class="inputbox" style="clear:both;height:100px;width:510px"></textarea>
				</dd>
			</dl>
				
			<dl>
				<dd>
					<input type="button" value="Adicionar passo" id="adpasso" class="button2"/>
					<input type="button" value="Remover passo" id="repasso" class="button2"/>
				</dd>
			</dl>
			
			<br/>
			
			<dl>
				<dd>
					<center>
						<input type="submit" tabindex="5" class="gerar" class="button1" onclick="gerar();" value="Gerar código do guia/tutorial"/>
					</center>
				</dd>
			</dl>
		</fieldset>
		
		<div style="margin: 5% 0% 0% 0%;"><center><textarea name="result" id="result" tabindex="4" class="inputbox" style="clear:both;height:200px;width:510px"></textarea></center></div>
		
		<script>
			//VARIÁVEIS
			var qnt					= 1;
			var $passo				= $("#passo");
			var $warningtext		= $("#warningtext");
			var $warningshow		= $("#warningshow");
			var $warninghide		= $("#warninghide");
			
			//AVISO
			$("#warningshow").on("click", function(){
				$warningtext.append('<br/><br/><dl id="avisowarng"><dt><label>Aviso:</label></dt><dd><textarea name="aviso" id="aviso" tabindex="4" class="inputbox" style="clear: both; height: 67px; width:510px;"></textarea></dd></dl>');
				
				$warninghide.show();
				$warningshow.hide();
			});
			
			$("#warninghide").on("click", function(){
				$warningtext.find("#avisowarng").remove();
				
				$warningshow.show();
				$warninghide.hide();
			});
			
			//TUTORIAL
			$("#adpasso").on("click", function(){
				$passo.append('<br/><br/><dl id="passo"><dt><label>'+(++qnt)+'º -</label></dt><dd><input type="text" name="titulopasso" id="titulopasso" size="25" tabindex="1" class="inputbox autowidth" style="clear:both;width:510px;color:darkblue;font-weight:bold" value=""/><br/><br/><textarea name="descricaopasso" id="descricaopasso" tabindex="4" class="inputbox" style="clear:both;height:100px;width:510px"></textarea></dd></dl>');
			});
			
			$("#repasso").on("click", function(){
				if(qnt==1) return 1;
				--qnt;
				$passo.find("#passo:last-child").remove();
			});
			
			//GERADOR
			function gerar(){
				var qnt						= 1;
				var qtn						= "\n\n";
				var ntq						= "\n\n[hr]\n[center][b][size=200]© [color=#1675bc]Advanced[/color] [color=#7BB92C]Roleplay[/color][/size][/b][/center]";
				var $title					= document.getElementById('title'),
					$descricao				= document.getElementById('descricao'),
					$avisos					= document.querySelectorAll('textarea[name="aviso"]'),
					$titulopassos			= document.querySelectorAll('input[name="titulopasso"]'),
					$descricaopassos		= document.querySelectorAll('textarea[name="descricaopasso"]'),
					$result					= document.getElementById('result');
				
				$result.value = '[h1]' + $title.value + '[/h1]\n\n[b]Descrição[/b]\n' + $descricao.value +'\n\n';
				
				$avisos.forEach(function($warning){
					$result.value += '[b]AVISO: [/b] ' + $warning.value + '\n\n[hr]\n\n';
				});
				
				$titulopassos.forEach(function($titlestep){
					$result.value += (qtn) + '[b]' + (qnt++) + ' - [color=red]' + $titlestep.value + '[/color][/b]';
				});
				
				$descricaopassos.forEach(function($descriptionstep){
					$result.value += '\n' + $descriptionstep.value;
				});
			}
		</script>
	</body>
</html>

Quando eu clico em gerar com 2 adicionar passo ativo. Ele gera o código desta maneira.

[h1]a[/h1]

[b]Descrição[/b]
b

[b]AVISO: [/b] c

[hr]



[b]1 - [color=red]d[/color][/b]

[b]2 - [color=red]f[/color][/b]
e
g

E deveria ser desta maneira...

[h1]a[/h1]

[b]Descrição[/b]
b

[b]AVISO: [/b] c

[hr]



[b]1 - [color=red]d[/color][/b]
e

[b]2 - [color=red]f[/color][/b]
g

Depois do G eu queria saltar 4 linhas. E adicionar como padrão uma frase. Pixel Gerator.

Ficando assim

[h1]a[/h1]

[b]Descrição[/b]
b

[b]AVISO: [/b] c

[hr]



[b]1 - [color=red]d[/color][/b]
e

[b]2 - [color=red]f[/color][/b]
g



[h2]PIXEL GERATOR[/h2]

Como posso fazer isso?

E mais uma vez muito obrigado.

Compartilhar este post


Link para o post
Compartilhar em outros sites

para pular linhas é só colocar mais \n, e no fim:

$result.value += '\n\n\n\n[h2]PIXEL GERATOR[/h2]';
sobre o erro, eu não entendi o que seria cada letra..

Compartilhar este post


Link para o post
Compartilhar em outros sites

Olá William, desculpa-me. Serei mais especifico desta vez.

Como pode ver no código. Ele funciona normalmente, sem "adicionar passo". Ao adicionar um passo ele meio que buga o texto a ser gerado no campo textarea. Em questões das letras foi eu que escrevi, pois estava com "preguiça de escrever" Título, Descrição, Aviso, Título Passo 1, Descrição Passo 1, Título Passo 2, Descrição Passo 2, assim sucessivamente. Se você tentar gerar o código você perceberá que está bugado.

Ao clicar em "Adicionar Passo" e ter dois passo criado para serem preenchidos e, logo após clicar em gerar. O resultado do texto a ser gerado será este.

[h1]Título[/h1]

[b]Descrição[/b]
Descrição...

[b]AVISO: [/b] Aviso...

[hr]



[b]1 - [color=red]Título Passo 1[/color][/b]

[b]2 - [color=red]Título Passo 2[/color][/b]
Descrição Passo 1...
Descrição Passo 2...

E ao clicar em gerar o texto deveria ser gerado desta forma.

[h1]Título[/h1]

[b]Descrição[/b]
Descrição...

[b]AVISO: [/b] Aviso...

[hr]



[b]1 - [color=red]Título Passo 1[/color][/b]
Descrição Passo 1...

[b]2 - [color=red]Título Passo 2[/color][/b]
Descrição Passo 2...

E gostaria de adicionar depois da descrição dos passo uma frase, ela em questão é: PIXEL GERATOR. Espero que tenha entendido o meu problema William.

Obrigado mais uma vez.

Compartilhar este post


Link para o post
Compartilhar em outros sites

ah sim.. então.. você vai ter que loopar junto o título e a descrição.

Em vez de ser um loop para o título e outro loop para a descrição, você vai ter que loopar os dois de uma única vez.

o texto vai após cada título e descrição? se for, é só colocar ele dentro do loop também.

Compartilhar este post


Link para o post
Compartilhar em outros sites

assim:

<html>
  <head>
    <title>Gerador de Guias e Tutoriais</title>
    <meta charset="UTF-8"/>
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.1.0.min.js"></script>

    <style type="text/css">
      fieldset dd input, fieldset dd textarea {
        margin-left: 5%;
      }
      .gerar {
        margin-top: 5%;
      }
    </style>
  </head>

  <body>
    <fieldset class="fields1">
      <dl>
        <dt>
          <label>Título:</label>
        </dt>

        <dd>
          <input type="text" name="title" id="title" required="required" size="25" class="inputbox autowidth" style="clear: both; width: 510px;" value=""/>
        </dd>
      </dl>

      <dl id="warningtext">
        <dt>
          <label>Descrição:</label>
        </dt>

        <dd>
          <textarea name="descricao" id="descricao" class="inputbox" style="clear: both; height: 100px; width:510px;"></textarea>
        </dd>
      </dl>

      <dl>
        <dd>
          <input type="button" id="warningshow" value="Adicionar aviso" class="button2"/>

          <input type="button" id="warninghide" value="Remover aviso" class="button2" style="display:none;"/>
        </dd>
      </dl>

      <dl id="passo">
        <dt>
          <label>1º -</label>
        </dt>

        <dd>
          <input type="text" name="titulopasso" id="titulopasso" placeholder="Título" size="25" class="inputbox autowidth" style="clear:both;width:510px;color:darkblue;font-weight:bold" value=""/>

          <br/><br/>

          <textarea name="descricaopasso" id="descricaopasso" placeholder="Descrição" class="inputbox" style="clear:both;height:100px;width:510px"></textarea>
        </dd>
      </dl>

      <dl>
        <dd>
          <input type="button" value="Adicionar passo" id="adpasso" class="button2"/>
          <input type="button" value="Remover passo" id="repasso" class="button2"/>
        </dd>
      </dl>

      <br/>

      <dl>
        <dd>
          <center>
            <input type="submit" class="gerar" class="button1" onclick="gerar();" value="Gerar código do guia/tutorial"/>
          </center>
        </dd>
      </dl>
    </fieldset>

    <div style="margin: 5% 0% 0% 0%;"><center><textarea name="result" id="result" class="inputbox" style="clear:both;height:200px;width:510px"></textarea></center></div>

    <script>
      //VARIÁVEIS
      var qnt             = 1;
      var $passo          = $("#passo");
      var $warningtext    = $("#warningtext");
      var $warningshow    = $("#warningshow");
      var $warninghide    = $("#warninghide");

      //AVISO
      $("#warningshow").on("click", function(){
        $warningtext.append('<br/><br/><dl id="avisowarng"><dt><label>Aviso:</label></dt><dd><textarea name="aviso" class="inputbox" style="clear: both; height: 67px; width:510px;"></textarea></dd></dl>');

        $warninghide.show();
        $warningshow.hide();
      });

      $("#warninghide").on("click", function(){
        $warningtext.find("#avisowarng").remove();

        $warningshow.show();
        $warninghide.hide();
      });

      //TUTORIAL
      $("#adpasso").on("click", function(){
        $passo.append('<br/><br/><dl id="passo"><dt><label>'+(++qnt)+'º -</label></dt><dd><input type="text" name="titulopasso" id="titulopasso" size="25" class="inputbox autowidth" style="clear:both;width:510px;color:darkblue;font-weight:bold" value=""/><br/><br/><textarea name="descricaopasso" id="descricaopasso" class="inputbox" style="clear:both;height:100px;width:510px"></textarea></dd></dl>');
      });

      $("#repasso").on("click", function(){
        if(qnt==1) return 1;
        --qnt;
        $passo.find("#passo:last-child").remove();
      });

      //GERADOR
      function gerar(){
        var qnt           = 1;
        var qtn           = "\n\n";
        var ntq           = "\n\n[hr]\n[center][b][size=200]© [color=#1675bc]Advanced[/color] [color=#7BB92C]Roleplay[/color][/size][/b][/center]";
        var $title          = document.getElementById('title'),
          $descricao        = document.getElementById('descricao'),
          $avisos           = document.querySelectorAll('textarea[name="aviso"]'),
          $titulopassos     = document.querySelectorAll('input[name="titulopasso"]'),
          $descricaopassos  = document.querySelectorAll('textarea[name="descricaopasso"]'),
          $result           = document.getElementById('result');

        $avisos           = [].slice.call($avisos);
        $titulopassos     = [].slice.call($titulopassos);
        $descricaopassos  = [].slice.call($descricaopassos);

        $result.value = '[h1]' + $title.value + '[/h1]\n\n[b]Descrição[/b]\n' + $descricao.value +'\n\n';

        $avisos.forEach(function($warning){
          $result.value += '[b]AVISO: [/b] ' + $warning.value + '\n\n[hr]\n\n';
        });

        $titulopassos.forEach(function($titlestep, i){
          $result.value += (qtn) + '[b]' + (qnt++) + ' - [color=red]' + $titlestep.value + '[/color][/b]';
          $result.value += '\n' + $descricaopassos[i].value;
          $result.value += '\n\n\n\n[h2]PIXEL GERATOR[/h2]';
        });

      }
    </script>
  </body>
</html>

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.