DevSamurai
DevSamurai

Reputation: 15

getting textarea value with newlines javascript

I have an HTML textarea and when data entered, and when submitted a js function takes values form textarea and puts them into a paragraph. but there is newline between textarea values and when the function takes those values it puts them without newlines in the paragraph. Is there any way to make newlines even after submitting?

<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<div>
<textarea type="text" id="Question1" rows="5" cols="60">
-text number 1.
-text number 2.
-text number 3.
-text number 4.
</textarea><br />
<button onclick="getUserInput1();">submit</button><br />
</div>
<div>
<p>this is text in the textarea <span class="myId1"></span>.</p>
</div>
<script>
function getUserInput1() {
        var value1 = document.getElementById("Question1").value;
        var capita = document.getElementsByClassName("myId1");
        for (var i = 0; i < capita.length; i++) {  
            capita[i].innerHTML = value1 + " ";
        }
}
</script>
</body>
</html>

Upvotes: 0

Views: 147

Answers (2)

Dimas Lanjaka
Dimas Lanjaka

Reputation: 294

Because newline in HTML is <br />. You should split the strings by newlines which can be parsed with regex /\r?\n/gm. using g for global flag and m for multi lines.

<div>
  <textarea type="text" id="Question1" rows="5" cols="60">
-text number 1.
-text number 2.
-text number 3.
-text number 4.
</textarea><br />
  <button onclick="getUserInput1();">submit</button><br />
</div>
<div>
  <p>this is text in the textarea <span class="myId1"></span>.</p>
</div>
<script>
  function getUserInput1() {
    var value1 = document.getElementById("Question1").value;
    var capita = document.getElementsByClassName("myId1");
    for (var i = 0; i < capita.length; i++) {
      capita[i].innerHTML = value1.split(/\r?\n/g).join('<br/>')
    }
  }
</script>

full example

Upvotes: 1

IT goldman
IT goldman

Reputation: 19440

It does collect the new lines, only HTML handles those as a single white space. That's why I replace all new lines \n with an html code of new line <br>

<!DOCTYPE html>
<html lang="en">

<head>
  <title>Document</title>
</head>

<body>
  <div>
    <textarea type="text" id="Question1" rows="5" cols="60">
-text number 1.
-text number 2.
-text number 3.
-text number 4.
</textarea><br />
    <button onclick="getUserInput1();">submit</button><br />
  </div>
  <div>
    <p>this is text in the textarea <span class="myId1"></span>.</p>
  </div>
  <script>
    function getUserInput1() {
      var value1 = document.getElementById("Question1").value.replace(/\n/g, "<br>");
      var capita = document.getElementsByClassName("myId1");
      for (var i = 0; i < capita.length; i++) {
        capita[i].innerHTML = value1 + " ";
      }
    }
  </script>
</body>

</html>

Upvotes: 0

Related Questions