Rich Text Editor in a Form
- Create the editor on a
<textarea name="…">. The editor replaces it on screen and keeps its value filled as the user types, so the HTML posts with the other fields. - Content you set from code with
setHTMLCode()is not copied until the user edits, so copygetHTMLCode()into the field in your submit handler. requireddoes not work on the hidden textarea. CheckgetCharCount()instead, as this form does.- Clean the posted HTML on the server before you store it.
<form id="ticket" method="post" action="/tickets">
<input name="subject" required>
<textarea id="body" name="body"></textarea>
<button type="submit">Send</button>
</form>
<script>
// Pass the textarea: the editor replaces it and keeps it filled as the user types.
var editor1 = new RichTextEditor("#body");
document.getElementById("ticket").addEventListener("submit", function (e) {
// Copy once more on submit, which also covers content set with setHTMLCode().
document.getElementById("body").value = editor1.getHTMLCode();
if (editor1.getCharCount() < 20) {
e.preventDefault();
alert("Please describe the problem in at least 20 characters.");
}
});
</script>Related: save and load content, word count and word limit.