How to apply a style to the html of a text selected from a textarea field?

Asked

Viewed 27 times

-1

Hello, I have a question about how to create an action (button) that when clicking on it will be applied initially a style to a selected text within a textarea field.

Yes it is like those same editors, where you select a piece of text, paragraph, etc. and apply a background color or same font color.

After some research I arrived at a code like this:

<!DOCTYPE html>
<html>
<head>
    <title>Test 89</title>
    <script type="text/javascript">
        function doBold(){
            var editor = document.getElementById("editor");
            var editorHTML = editor.innerHTML;
            var selectionStart = 0, selectionEnd = 0;
            if (editor.selectionStart) selectionStart = editor.selectionStart;
            if (editor.selectionEnd) selectionEnd = editor.selectionEnd;
            if (selectionStart != selectionEnd) {
                var editorCharArray = editorHTML.split("");
                editorCharArray.splice(selectionEnd, 0, "</b>");
                editorCharArray.splice(selectionStart, 0, "<b>"); //must do End first
                editorHTML = editorCharArray.join("");
                editor.innerHTML = editorHTML;
            }
        }
    </script>
</head>
<body>
    <textarea id="editor" cols="80" rows="20">This is some text to see what happens and when. You should be able to select some text in here then click the "Bold" button to make it bold.</textarea><br />
    <button onclick="doBold()">Bold</button>
</body>
</html>

But in this code what happens is that it applies the as if it were just an actual text, but I want it to apply as if it were behind the html and of course giving the highlighting in the text.

Because the html content will be saved in the database.

1 answer

1

The element textarea is used for text, not content html.

The HTML element represents a multi-line Plain-text Editing control, Useful when you want to allow users to enter a sizeable amount of free-form text, for example a comment on a review or feedback form.

Of the documentation here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea

That is, the Plain-text means that only text can be used. The element can be stylized, but will format all the text contained in it.

For what you want to do, you should use an element with div for example, which supports content html.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.