Hello,
I am working on an edit comment script that will allows users to edit their comments, this is done with JavaScript/Jquery.
The end goal is simply to allow users to click the “Edit” button, which will convert the comment to an editable element, this could either be a textarea, or a div with contenteditable enabled, which of those is best i do not know and would appreciate clarification on since i could not find an answer for that online.
In the mean time, i have tried using a contenteditable div.
Clicking on the “Edit” button adds some styles to make the div look like a textarea, and i added the contenteditable attribute to make the element editable.
There is also a listener on the element that when saving the edit (either by clickin on the “save” button or pressing ctrl+enter), the div element will revert back to what it was with the new text, and the new text will be sent to the database through ajax.
The issue that i am having with this is that i cannot figure out how to properly get the correctly formatted data, for example, when i enter this in to the element:
test1
test2
Its output is actually:
test1
test2
An extra line break is added, and when i see what the code actually shows, it shows this:
test1<div><br></div><div>test2</div>
I have tried a few different things, but nothing has worked so far, i also tried document.execCommand("defaultParagraphSeparator", false, "p");
but that didnt work either.
The code i am using to get the new text from the contenteditable div is this:
commentTextNew = formElements['commentTextEle'].html().trim()
.replace(/<br\s*\/*>/ig, '\n')
.replace(/(<(p|div))/ig, '\n$1')
.replace(/(<([^>]+)>)/ig, "");
which outputs:
test1
test2
(adding an extra line break).
Any thoughts? maybe using a textarea is better and just switching between them is a better option?
This comment system is based on javascript/jquery, so when the new comment is saved, it does it through ajax, so a full form isnt required, only the textarea/editable div.