Reputation: 1775
I have a pre
tag that displays text taken from a database (notes for a shopping order). I use the pre tag because it displays new lines.
I use contenteditable="true"
on it so that users can edit the field, and click a save button to save it.
However upon saving, when I take the field's value using field.text()
, the new lines are not preserved.
Reproduce:
HTML:
<pre id="notes" contenteditable="true">Some
test
Txt
</pre>
JS:
// Works fine here
console.log($('#notes').text());
// add some text with new lines, then "blur" the text and you can see the issue happening in the log -- new lines not preserved
$('#notes').on('blur', function (e) {
console.log($('#notes').text());
});
What I am trying but so far haven't succeeded
// When user presses enter on an editable field.
$('#notes').on('keydown', function (e) {
if (e.keyCode === 13) {
// trap the return key being pressed and insert new line at THIS place --- how??? (Possibly not the most elegant solution either)
}
});
https://jsfiddle.net/6496pke5/
Upvotes: 4
Views: 8779
Reputation: 11
I recommend use a hidden tag pre and code for event 'blur' as shown as below.
$('#notes-text').text($('#notes').html().replace(/<br>/g, '\n'));
console.log($('#notes-text').text());
console.log($('#notes').text());
$('#notes').on('keydown', function(e) {
if (e.keyCode === 13) {
document.execCommand('insertHTML', false, '<br>');
return false;
}
});
$('#notes').on('blur', function() {
$('#notes-text').text($('#notes').html().replace(/<br>/g, '\n'));
console.log($('#notes-text').text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<pre id="notes" contenteditable="true">Some
test
Txt
</pre>
<pre id="notes-text" style="display: none;"></pre>
Upvotes: 0
Reputation: 321
Use html() instead of text() in order to create a break line on hit Enter.
Using html() will wrap a <br>
tag into a <div>
element though, to prevent that behaviour use document.execCommand() method:
$('#notes').on('keydown', function (e) {
if (e.keyCode === 13) {
document.execCommand('insertHTML', false, '<br>');
return false;
}
});
Here is fiddle https://jsfiddle.net/6496pke5/1/
Upvotes: 2
Reputation: 68393
It won't because you are doing
console.log($('#notes').text());
since when you press enter
to create a new line <br>
is added to the markup which will not come in the textContent
attribute of the element
of which .text()
is a short form of.
try instead
console.log($('#notes').html());
you will see the new lines <br>
added.
Upvotes: 0