简体   繁体   中英

Get selected text in textarea

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.

Thanks in advance.

UPDATE:

Thanks George, I've tried the example that you 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 . Any idea whats wrong with my code? Thanks.

<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>

UPDATE 2:

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

I believe that this question has what you're looking for: How to get selected text in textarea?

Edit:

This may also prove useful (linked in that question):

Understanding what goes on with textarea selection with JavaScript

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;
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM