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>
Advertisement
Answer
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>