views:

120

answers:

2

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

+1  A: 

I believe that this question has what you're looking for: http://stackoverflow.com/questions/717224/how-to-get-selected-text-in-textarea

Edit:

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

http://stackoverflow.com/questions/401593/javascript-textarea-selection

George Marian
Hi, I can get some of it but not all of it to work, see the update of my question. Thanks.
usertest
@user201140 You had no way of knowing, but I was already looking into it. I noticed the question had bubbled up on the front page. See my comment to your question.
George Marian
Thanks, I've just found another plugin to the one you pointed out I'm not sure if there based on the same thing. I cut the example down (which included buttons) to what I needed and it seems to work. Its here - http://plugins.jquery.com/project/a-tools
usertest
A: 

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