Ammy Dua Ammy Dua - 4 months ago 17
jQuery Question

HTML - Break Line While Getting Input From TextArea

My Problem Is,

When I Type Multi Lines In TextArea I Get Output Like This,

upper one is input and lower one is output

But I Want To Get Output Like This,

Image 2

In This Photo I Used

<br/>
Just For Making The Look What I Want But, In Real I Don't Want To Use
<br/>
To Break Line In Multi Line

This Is Th Code I'm Using...

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<TextArea id = "Input" onKeyupUp = "showResult()" style = "height: 100px; width: 100%; resize: none;"> </TextArea>
<Div id = "output" ></Div>
</body>

<script>
function showResult(){
var input = document.getElementById("Input").value;
document.getElementById("Output").innerHTML = input;
}
</script>
</html>

Answer

The textarea uses newline in text format like \n or \r or \r\n. So, simple regex to convert anyof these to HTML newline: <br /> will solve your issue.

var inputHTML = input.replace(/\r\n|\r|\n/g, "<br />");

function showResult() {
  var input = document.getElementById("Input").value;
  var inputHTML = input.replace(/\r\n|\r|\n/g, "<br />");
  document.getElementById("output").innerHTML = inputHTML;
}
<!DOCTYPE html>
<html>

<head>
</head>

<body>
  <TextArea id="Input" onKeyupUp="showResult()" style="height: 100px; width: 100%; resize: none;"></TextArea>
  <Div id="output"></Div>
  <button onclick="showResult()">SHOW</button>
</body>

</html>

Comments