Home > Enterprise >  getting textarea value with newlines javascript
getting textarea value with newlines javascript

Time:09-29

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 ></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>

CodePudding user response:

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 ></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>

CodePudding user response:

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

<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 ></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

  • Related