Shawn
Shawn

Reputation: 132

Split value from textarea by line break and add text indent to each of them (Javascript)

I am spliting the value from textarea by line break and add text indent to each of them.

Here is my code:

function splits() {
  let textarea = document.getElementsByTagName("textarea")[0]
  let arrays = textarea.value.split(/\r?\n/)
  for (let i = 0; i < arrays.length; i++) {
    textarea.style.textIndent = "10px"
    textarea.value = "<p>" + arrays[i] + "</p>"
    //not working return "<p>(The content I entered)</p>
  }
}
<textarea></textarea>
<button onclick=splits()>Splits</button>

I want to make each of the elements from the arrays be in a new <p>.

However, my code above is obviously not working.

Do anyone know anyone to do this?

Thanks for any helps and responds.

Upvotes: 0

Views: 861

Answers (2)

navnath
navnath

Reputation: 3714

This is not possible to do with a textarea. What you are looking for is an content editable div

function splits(){
  const div = document.getElementById("test");
  let values = div.innerText.split(/\r?\n/)
  div.innerHTML = values.map(sentence => `<p>${sentence}</p>`).join("");
  div.style.textIndent = "10px";
}
div#test {
    width: 300px;
    height: 200px;
    border: 1px solid #ccc;
}
<div contenteditable="true" id="test"></div>
<button onclick=splits()>Splits</button>

Upvotes: 2

Barmar
Barmar

Reputation: 780889

You're replacing the textarea value each time through the loop, rather than appending to it.

You also don't need to set the style each time through the loop, you can do that just once.

function splits() {
  let textarea = document.getElementsByTagName("textarea")[0]
  let arrays = textarea.value.split(/\r?\n/)
  textarea.style.textIndent = "10px"
  textarea.value = arrays.map(s => `<p>${s}</p>`).join("");
}
<textarea></textarea>
<button onclick=splits()>Splits</button>

Upvotes: 2

Related Questions