Reputation: 178
I have a text area, a button and a div
<textarea type="text" id="mytext"></textarea>
<button onclick="test()">Click Me</button>
<div id="here"></div>
Here is the script
<script>
function test() {
var b = document.getElementById('mytext').value;
document.getElementById('here').innerHTML = b;
}
</script>
I wrote following text in text area:
Hello All
Good Morning
But when i pressed Click Me, it gives following text in div element:
Hello All Good Morning
How to show multiple lines as in textarea? Thanks
Upvotes: 3
Views: 5593
Reputation: 159
Fixing text area and div size with br replace is giving effective result.
function test() {
var b = document.getElementById('mytext').value;
document.getElementById('here').innerHTML = b.replace(/\n\r?/g, '<br>');
}
#here {
width: 100px;
height: 100px;
word-wrap: break-word;
}
#mytext {
width: 100px;
height: 100px;
}
<textarea type="text" id="mytext"></textarea>
<button onclick="test()">Click Me</button>
<div id="here"></div>
Upvotes: 0
Reputation: 1426
You have to replace the new line with br tag.
Example Code
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<textarea type="text" id="mytext"></textarea>
<button onclick="test()">Click Me</button>
<div id="here"></div>
</body>
<script type="text/javascript">
function test() {
var b = document.getElementById('mytext').value;
b = b.replace(/\r|\n/,"<br>");
document.getElementById('here').innerHTML = b;
}
</script>
</html>
Upvotes: 1
Reputation: 1485
You should replace new line characters with <br>
tag.
function test() {
var b = document.getElementById('mytext').value;
document.getElementById('here').innerHTML = b.replace(/\n\r?/g, '<br>');
}
<textarea type="text" id="mytext"></textarea>
<button onclick="test()">Click Me</button>
<div id="here"></div>
Upvotes: 0
Reputation: 801
just use replace(/(?:\r\n|\r|\n)/g, '<br />');
to replace all line breaks in a string with <br />
tag like:
function test() {
var b = document.getElementById('mytext').value;
b = b.replace(/(?:\r\n|\r|\n)/g, '<br />');
document.getElementById('here').innerHTML = b;
}
<textarea type="text" id="mytext"></textarea>
<button onclick="test()">Click Me</button>
<div id="here"></div>
Upvotes: 2
Reputation: 217
Example Split a string into an array of substrings:
var str = "How are you doing today?";
var res = str.split(" ");
//The result of res will be an array with the values:
Output: How,are,you,doing,today?
Upvotes: -1