JRowan
JRowan

Reputation: 7104

using a div contentEditable innerText and innerHTML neither have newlines to and from database

I'm using a div for people to enter text and then I tried saving

div.innerText

and

div.innerHTML

to my database but when I bring it back from the database and put it back into the div all of the carriage returns or newlines are gone

innerHTML to database

a

b

c

    //in database like this  <div>a</div><div></div><div>b</div><div></div><div>c</div>

innerText to database

a
a
a
a
a
a
    //how it stored in database  aaaaaa

if you could tell me how to handle this situation I would appreciate it greatly thank you for your time

Upvotes: 3

Views: 3580

Answers (2)

webFashion
webFashion

Reputation: 748

div.innerHTML creates an HTML output of your new lines using <div> containers. Therefore the line breaks will be "replaced".

div.innerText uses the "invisible" character \n or \r\n to mark new lines and it is possible that they are not shown in your database. You can however replace them by <br> tags to see if they are there.

document.getElementById("output").addEventListener("click", function() {
  console.log("HTML:");
  console.log(document.getElementById("text").innerHTML);
  console.log("Text:");
  var text = document.getElementById("text").innerText;
  console.log(text.replace(/(?:\r\n|\r|\n)/g, '<br>'));
});
#text {
  background-color:#FAFAFA;
  border: red solid 1px;
  height:150px;
  width: 200px;
}
<button id="output">
  Show in console
</button>

<div id="text" contenteditable>

</div>

console.log(text.replace(/(?:\r\n|\r|\n)/g, '<br>')); replaces all different kinds of possible new lines into <br> tags.

Upvotes: 2

guest271314
guest271314

Reputation: 1

You can substitute <textarea> element for <div> with contenteditable attribute set. Encode, decode .value of textarea using encodeURIComponent(), decodeURIComponent() or format data as JSON utilizing JSON.stringify(), JSON.parse()

var button = document.querySelector("button")
var textarea = document.querySelector("textarea");
button.onclick = function() {
  var value = textarea.value
  console.log(encodeURIComponent(value)
             , decodeURIComponent(value)
             , JSON.stringify(value)
             , JSON.parse(JSON.stringify(value))
             );
}
textarea {
  border: 1px solid navy;
  width: 300px;
  height: 200px;
}

You can use
<button>click</button><br>
<textarea></textarea>

Upvotes: 0

Related Questions