1

I'd like to store selected text in a variable and then delete the selected text by pressing a button. Preferably with jQuery, but I don't mind basic JavaScript.


I've tried the example that pointed to stripping down the code to what I need, but I can't get it to work on click for the button. It only works if I change #addchapter to textarea. what’s wrong with my code?

<html>

<head>
    <script type="text/javascript" src="jquery-latest.pack.js"></script>
    <script type="text/javascript" src="jquery-fieldselection.js"></script>
    <script type="text/javascript"><!--//--><![CDATA[//><!--

        $(document).ready(function(){

            $('#addchapter').click(update);
        });

        function update(e) {

            var range = $(this).getSelection();

            $('#output').html(
                "selected text:\n<span class=\"txt\">" + ((true) ? range.text.whitespace() : range.text) + "</span>\n\n"
            );
        }

        String.prototype.whitespace = (function() {

            if (!RegExp.escape) {
              RegExp.escape = (function() {
                var specials = [ '/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\' ];
                var sRE = new RegExp( '(\\' + specials.join('|\\') + ')', 'g' );
                return function(text) { return text.replace(sRE, '\\$1') }
              })();
            }

            var ws = { "\r\n": "¶", "\n": "¶", "\r": "¶", "\t": "&raquo;", " ": "&middot;" };

            return ($.browser.msie) ? function() {

                var s = this;
                $.each(ws, function(i){ s = s.replace(new RegExp(RegExp.escape(i), 'g'), this) });
                return s;
            } : function () {
                var s = this;
                $.each(ws, function(i){ s = s.replace(new RegExp(RegExp.escape(i), 'g'), this + "\u200b") });
                return s;
            }
        })();

        //--><!]]>

    </script>

</head>

<body>
    <pre id="output"></pre>

    <textarea id="area1" name="area1">textarea: foo bar baz</textarea>

    <input type="button" value="add" id="addchapter">
</body>

</html>

I ended up using this - http://plugins.jquery.com/project/a-tools

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
usertest
  • 27,132
  • 30
  • 72
  • 94
  • Just an educate guess, but I think you need to hook in your even handler at the end of the script block. IIRC, the JavaScript is being evaluated as it's read in that block, as opposed to reading the entire file when including code from an external file. i.e. move `$(document).ready(function(){ $('#addchapter').click(update); });` to the end of the script block. – George Marian Jul 11 '10 at 00:31
  • Hi, just tried that but it doesn't seem to work. – usertest Jul 11 '10 at 16:40
  • Possible duplicate: *[How can I get the selected text in a textarea?](https://stackoverflow.com/questions/717224/how-can-i-get-the-selected-text-in-a-textarea)* – Peter Mortensen May 09 '22 at 15:07
  • The `plugins.jquery.com` link is (effectively) broken: *"This is somewhat embarrassing, isn’t it? It seems we can’t find what you’re looking for."* – Peter Mortensen May 09 '22 at 15:25

1 Answers1

0

The question seems clear enough but then the code is confusingly unrelated, so I'm going to answer the question as I understood it without the code.

The deleteSelectedText() function will delete the selected text from a <textarea> or <input type="text"> you provide and return you the text that was deleted.

function getSelectionBoundary(el, start) {
    var property = start ? "selectionStart" : "selectionEnd";
    var originalValue, textInputRange, precedingRange, pos, bookmark, isAtEnd;

    if (typeof el[property] == "number") {
        return el[property];
    } else if (document.selection && document.selection.createRange) {
        el.focus();

        var range = document.selection.createRange();
        if (range) {
            // Collapse the selected range if the selection is not a caret
            if (document.selection.type == "Text") {
                range.collapse(!!start);
            }

            originalValue = el.value;
            textInputRange = el.createTextRange();
            precedingRange = el.createTextRange();
            pos = 0;

            bookmark = range.getBookmark();
            textInputRange.moveToBookmark(bookmark);

            if (/[\r\n]/.test(originalValue)) {
                // Trickier case where input value contains line breaks

                // Test whether the selection range is at the end of the
                // text input by moving it on by one character and
                // checking if it's still within the text input.
                try {
                    range.move("character", 1);
                    isAtEnd = (range.parentElement() != el);
                } catch (ex) {
                    log.warn("Error moving range", ex);
                    isAtEnd = true;
                }
                range.moveToBookmark(bookmark);

                if (isAtEnd) {
                    pos = originalValue.length;
                } else {
                    // Insert a character in the text input range and use
                    // that as a marker
                    textInputRange.text = " ";
                    precedingRange.setEndPoint("EndToStart", textInputRange);
                    pos = precedingRange.text.length - 1;

                    // Delete the inserted character
                    textInputRange.moveStart("character", -1);
                    textInputRange.text = "";
                }
            } else {
                // Easier case where input value contains no line breaks
                precedingRange.setEndPoint("EndToStart", textInputRange);
                pos = precedingRange.text.length;
            }
            return pos;
        }
    }
    return 0;
}

function deleteSelectedText(el) {
    var start = getSelectionBoundary(el, true);
    var end = getSelectionBoundary(el, false);
    var val = el.value;
    var selectedText = val.slice(start, end);
    el.value = val.slice(0, start) + val.slice(end);
    return selectedText;
} 
Tim Down
  • 318,141
  • 75
  • 454
  • 536