I do need the line breaks, but even with wrap="hard", defining cols, the value is still a single line.
<!DOCTYPE html>
<html>
<body>
<h1>The textarea wrap attribute</h1>
<textarea id="usrtxt" rows="2" cols="5" name="usrtxt" wrap="hard" style="overflow-wrap: break-word; width: 100px;">
At W3Schools you will find free Web-building tutorials.
</textarea>
<!-- A div to display the textarea content -->
<div id="textareaContent"></div>
<script>
// Function to display textarea content
function showTextareaContent() {
var textarea = document.getElementById('usrtxt');
var displayArea = document.getElementById('textareaContent');
displayArea.innerText = textarea.value;
}
// Event listener for the textarea input
document.getElementById('usrtxt').addEventListener('input', showTextareaContent);
// Initialize the display area with the current content of the textarea
showTextareaContent();
</script>
</body>
</html>
The wrap attribute - the key part is "for form submission".
Indeed the textarea's value does not contain the added \n
s.
By adding a form element wrapping the textarea, you can use FormData to obtain the formatted text.
<!DOCTYPE html>
<html>
<body>
<h1>The textarea wrap attribute</h1>
<form>
<textarea name="usrtxt" id="usrtxt" rows="2" cols="5" name="usrtxt" wrap="hard" style="overflow-wrap: break-word; width: 100px;">
At W3Schools you will find free Web-building tutorials.
</textarea>
</form>
<!-- A div to display the textarea content -->
<div id="textareaContent"></div>
<script>
// Function to display textarea content
function showTextareaContent() {
var textarea = document.getElementById('usrtxt');
let form = textarea.form;
let fd = new FormData(form);
let formatted = fd.get("usrtxt"); // this uses the "name" property of the textarea element
var displayArea = document.getElementById('textareaContent');
displayArea.innerText = formatted;
}
// Event listener for the textarea input
document.getElementById('usrtxt').addEventListener('input', showTextareaContent);
// Initialize the display area with the current content of the textarea
showTextareaContent();
</script>
</body>
</html>