user1260310
user1260310

Reputation: 2227

Select text and format a 'textarea' using JavaScript

I'm trying to allow users to do simple formatting of text in a textarea used in a comment system (a poor man's text editor). I wWould like to allow them to select text with the cursor and then click on a button to format it. How do I get the JavaScript to grab and return the selected text?

Imagine it should be something like:

<script>
    function formatText(field) {
        // Gets text
        var text;
        text = field.value.substring(field.selectionStart, field.selectionEnd);

        // Formats it
        var text = '<b'> + text + '</b>';

        // Returns it
        field.value.substring(field.selectionStart, field.selectionEnd); = text;
    }
</script>

<body>
    <textarea id="field"></textarea><button onclick="formatText('field')">Make bold</button>
</body>

The following code gets selected text, formats it and then sends it back to the textarea—however, it replaces all text in the textarea... So I just need way to replace the selected text in the textarea—rather than all--and I'll be done:

<head>
    <script type="text/javascript">
        function GetSelection () {
            var selection = "";

            var textarea = document.getElementById("field");
            if ('selectionStart' in textarea) {
                // Check whether some text is selected in the textarea
                if (textarea.selectionStart != textarea.selectionEnd) {
                    selection = textarea.value.substring(textarea.selectionStart,

                    textarea.selectionEnd);
                }
            }
            else {  // Internet Explorer before version 9
                    // create a range from the current selection

                var textRange = document.selection.createRange ();

                // Check whether the selection is within the textarea
                var rangeParent = textRange.parentElement ();
                if (rangeParent === textarea) {
                    selection = textRange.text;
                }
            }

            if (selection == "") {
                alert ("No text is selected.");
            }
            else {
                selection = "<b>" + selection + "</b>";
                document.getElementById('field').value = selection;
            }
        }
    </script>
</head>

<body>
    <textarea id="field" spellcheck="false">Select some text within this field.</textarea>
    <button onclick="GetSelection ()">Get the current selection</button>
</body>

I think there is a way to specify document.getElementByID.value.substr which might do it, but I don't know syntax.

Upvotes: 0

Views: 7563

Answers (2)

user1260310
user1260310

Reputation: 2227

Here it is: A poor man's text editor. It uses SelectionStart and SelectionEnd applied to text from a textarea to get the selected text.

Then after reformatting, it puts the textarea text back together from three pieces, before the selection text, the selected text and after the selection text. It puts it back in the textarea using document.getElementById('textareaid').value = assembled text.

<html>

<head>
    <script>
        function format () {
            // Code for Internet Explorer
            var textarea = document.getElementById("textarea");

            if (document.selection)
            {
                textarea.focus();
                var sel = document.selection.createRange();

                // Alert the selected text in textarea
                alert(sel.text);

                // Finally replace the value of the selected
                // text with this new replacement one
                sel.text = '<b>' + sel.text + '</b>';
            }

            // Code for Mozilla Firefox

            var textarea = document.getElementById("textarea");

            var len = textarea.value.length;
            var start = textarea.selectionStart;
            var end = textarea.selectionEnd;
            var sel = textarea.value.substring(start, end);

            // This is the selected text and alert it
            //alert(sel);

            var replace = '<b>' + sel + '</b>';

            // Here we are replacing the selected text with this one
            textarea.value = textarea.value.substring(0, start) + replace + textarea.value.substring(end, len);

            var formatted = textarea.value;
            document.getElementById('field').value = formatted;
        }
    </script>
</head>

<body>
    <textarea id="textarea">One two three four five six seven eight</textarea><button onclick="format

    ()">Format selected text</button>
</body>
</html>

Upvotes: 2

Sully
Sully

Reputation: 14943

In your code there were the following issues:

  1. var text

    Each line must end with a ;

  2. <button onclick="formatText("field")">

    Starting a quote must end with a quote. If you need quotes within, i.e., for strings like "this is my text I want to process", then those quotes inside need to be single-quotes

    onclick="formatText('field')"
    
  3. text = field.value.substring(field.selectionStart, field.selectionEnd);

    The code was passing a string to the function, which doesn’t have a value property\method. We want the text in the textfield, so we use the 'element' that is holding it using document.getElementById('field').

    Then we just style that element which will do the trick.

    If you need to replace the text, just assign the value to

     document.getElementById('field').value = ...
    

Here is an example...

    <script type="text/javascript" >
        function formatText() {
            // Gets text
            //text = document.getElementById('field').value;

            // Formats it
            document.getElementById('field').style.fontWeight = "bold";
        }
    </script>
</head>

<body>
    <textarea id="field"></textarea><button onclick="formatText()">Make bold</button>
</body>

Check it at http://jsfiddle.net/YcpUs/.

Upvotes: 1

Related Questions