Take text area values separated by line

Asked

Viewed 710 times

2

How to take the value of textarea separated by line and add a div?

I would like to write a text on textarea separated by lines and sent to the other textarea by adding a div with the attribute class with increasing numbers on each row as in the examples below:

My code (which only works with 1 line):

function text(){

   var txt = document.getElementById('txt')
   var ext = document.getElementById('ext')

   ext.value = "<div class='classe1'>" +txt.value+ "</div>"
}
<textarea id="txt" oninput="text()"></textarea><br><textarea id="ext"></textarea>

Example of where I’m going with this:

<textarea style='height:60px;'>Texto 1
Texto 2
Texto 3</textarea><br>
<textarea id="txt" style='height:60px;'><div class="class1">Texto 1</div>
<div class="class2">Texto 2</div>
<div class="class3">Texto 3</div></textarea>

  • Explain further your doubt, got a little confused.

  • It’s not related to the answer, but <div> does not have the attribute name (at least in valid HTML). What you need the name? You could use id or class if only for HTML manipulation or <input type="hidden"> if to send the data in separate inputs.

  • It’s just an example I could simply change to class

3 answers

5


Breaking the problem into pieces can be solved as follows:

Assuming that a textarea contains the text:

abc
123

xyz
  1. Break your text into an array using String.split;

    let linhas = txt.value.split('\n')
    // ["abc", "123", "", "xyz"]
    
  2. [Optional] remove blank lines to not generate <div>s empty using Array.filter;

    let linhas_nao_vazias = linhas.filter(linha => linha.trim())
    // ["abc", "123", "xyz"]
    
  3. Add the text of each line inside the <div> using Array.map and Template strings

    let divs = linhas_nao_vazias.map((linha, i) => `
        <div class="texto${i+1}">
            ${linha}
        </div>
    `)
    // [
    //     "<div class=\"texto1\">abc</div>", 
    //     "<div class=\"texto2\">123</div>", 
    //     "<div class=\"texto3\">xyz</div>"
    // ]
    
  4. Unite the <div>s in a single string with Array.join

    // quebra de linha apenas para visual, poderia ser ''
    let resultado = divs.join('\n')
    // "<div class=\"texto1\">abc</div>
    // <div class=\"texto2\">123</div>
    // <div class=\"texto3\">xyz</div>"
    
  5. Assign the result to another <textarea>

    outro_txt.value = resultado
    

In the end it’s simple:

let txt = document.getElementById('texto')
let resultado = document.getElementById('resultado')

txt.addEventListener('keyup', () => {
    resultado.value = txt.value
        .split('\n')
        .filter(linha => linha.trim())
        .map((linha, i) => `<div class="linha${i+1}">${linha}</div>` )
        .join('\n')
})
textarea { width: 100% }
<textarea id="texto" rows=4></textarea>
<hr>
<textarea id="resultado" rows=4></textarea>

2

You can do using the split() to compile a list of the lines and traverse it by placing the tags of <div> and adding in ext:

function text(){

   var txt = document.getElementById('txt')
   var ext = document.getElementById('ext')

   var list = txt.value.split("\n")

   ext.value = ""
   for (var i = 0; i < list.length; i++){
       if (list[i].length > 0) {
           ext.value += "<div>"+list[i]+" "+i+"</div>"
       }
   }
}
<textarea id="txt" oninput="text()"></textarea><br><textarea id="ext"></textarea>

  • I updated the question.

  • if I want to add a growing number along with the div, for example in the attribute class: <div class="class1">Texto</div> afterward <div class="class2">Outro texto</div> how do I do?

  • @Mark by changing the foreach by a conventional is you get the number corresponding to the position of the item.

2

Another option with regex.

function texto(){
   /// a chamada `texto.call(this)` faz com que nexte momento this seja o textarea
 
   var value = this.value,
       dest = document.getElementById('etxt'); // textarea destino

   dest.value = ""; // <- limpa o valor anterior
   
   var i=0; // <- contador
   value.replace(/([^\n\r]+)/g, // <- regex qualquer valor que não seja nova linha
       function(x){ // <- funcão chamada para cada linha
           i++; // <- incrementa contador
           dest.value += "<div>"+x+" "+i+"</div>\n"; 
          //     ^                     ^
          //     |                     contador
          //     entra com o novo valor no textarea destino

       }
   );
}
<textarea id='txt' oninput='texto.call(this)'></textarea><br/>
<textarea id='etxt'></textarea>

  • I updated the question, summarizing: If I want to add an increasing number along with the div, for example in the class attribute: <div class="class1">Texto</div> afterward <div class="class2">Outro texto</div> how do I do?

  • 1

    Or in the same text type: <div>Texto 1</div> <div>Texto 2</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.