All demos ↓← All 93 demos

Rich Text Editor in a Form

Edit content, then include its HTML in a form submission.

For empty documents and required fields, follow the form validation guide.

  • 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 copy getHTMLCode() into the field in your submit handler.
  • required does not work on the hidden textarea. Check getCharCount() 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.

Use this in your app

This demo runs the same editor you get for every framework. See how to add it to yours: