How to insert paragraphs and then recognize them with a textarea

Asked

Viewed 358 times

1

I wonder how I could do to insert and then recognize in my code specific paragraph moments in typing in a textarea.

Example: inserir a descrição da imagem aqui

This is my textarea.

I want to rescue the content of this textarea and insert it into another <div> the same divides the paragraphs by inserting each of them in a <p>. So how would it look in the code:

<div class="wrapper">
   <p>É claro que a adoção de políticas descentralizadoras ainda não demonstrou convincentemente que vai participar...</p>
   <p>A nível organizacional, o novo modelo estrutural aqui preconizado nos obriga à análise da gestão inovadora da qual fazemos parte...</p>
   <p>Assim mesmo, a hegemonia do ambiente político estende o alcance e a importância de alternativas às soluções ortodoxas...</p>
</div>

How to do this?

1 answer

2


I believe you can take the string value of your textarea and give a split in the "\n" to split the lines into one array. Then just go through and create an element p, by inserting the value of the line into it, using a append to insert into .wrapper. How will you use the append, would always have to "clean" the contents of it.

Behold:

var textarea = document.querySelector('#textarea');
var wrapper = document.querySelector('.wrapper');



textarea.addEventListener('input', function () {
   
   var parts = this.value.split("\n");
   
  wrapper.innerHTML = '';
  
  parts.forEach(function (part) {
     var p = document.createElement('p');
     
     p.innerText = part;
     
     wrapper.append(p)
  })
   
})
<div class="wrapper"></div>
<textarea id="textarea"></textarea>

I did so because you made sure it was with the tag p. However, if the need is to display line breaks, you can simply insert the value of the textarea into .wrapper and stylize the same with the attribute white-space, with pre-wrap or wrap.

Thus:

var wrapper = document.querySelector('.wrapper');
var textarea = document.querySelector('.textarea');


textarea.addEventListener('input', function () {
  wrapper.innerHTML = this.value;

})
.wrapper{
 white-space: pre-wrap;
 }
<div class="wrapper"></div>

<textarea class="textarea"></textarea>

This property causes CSS to render the line breaks you add to textarea.

Note: In the example above, how I used innerHTML, have to be careful with XSS Injection. You can use innerText optionally, which apparently adds a <br /> when you put the line break in the textarea

  • but then in blank stretches there is a hidden n?

  • @Nicolass. in fact, the line break is a character, which can be represented by "\n" (has to be double quotes, single does not work)

Browser other questions tagged

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