42

I have a textbox and a link button. When I write some text, select some of it and then click the link button, the selected text from textbox must be show with a message box.

How can I do it?


When I click the submit button for the textbox below, the message box must show Lorem ipsum. Because "Lorem ipsum" is selected in the area.


If I select any text from the page and click the submit button it is working, but if I write a text to textbox and make it, it's not. Because when I click to another space, the selection of textbox is canceled.

Now problem is that, when I select text from textbox and click any other control or space, the text, which is selected, must still be selected.

How is it to be done?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mavera
  • 3,171
  • 7
  • 45
  • 58
  • I thins you should look to selectionstart/selectionend properties of the input field for firefox and textrange in IE some reference : [http://www.dedestruct.com/2008/03/22/howto-cross-browser-cursor-position-in-textareas/](https://web.archive.org/web/20090904134938/http://www.dedestruct.com/2008/03/22/howto-cross-browser-cursor-position-in-textareas/) – MatthieuGD Nov 09 '08 at 09:34

6 Answers6

45

OK, here is the code I have:

function ShowSelection()
{
  var textComponent = document.getElementById('Editor');
  var selectedText;

  if (textComponent.selectionStart !== undefined)
  { // Standards-compliant version
    var startPos = textComponent.selectionStart;
    var endPos = textComponent.selectionEnd;
    selectedText = textComponent.value.substring(startPos, endPos);
  }
  else if (document.selection !== undefined)
  { // Internet Explorer version
    textComponent.focus();
    var sel = document.selection.createRange();
    selectedText = sel.text;
  }

  alert("You selected: " + selectedText);
}

The problem is, although the code I give for Internet Explorer is given on a lot of sites, I cannot make it work on my copy of Internet Explorer 6 on my current system. Perhaps it will work for you, and that's why I give it.

The trick you look for is probably the .focus() call to give the focus back to the textarea, so the selection is reactivated.

I got the right result (the selection content) with the onKeyDown event:

document.onkeydown = function (e) { ShowSelection(); }

So the code is correct. Again, the issue is to get the selection on click on a button... I continue to search.

I didn't have any success with a button drawn with a li tag, because when we click on it, Internet Explorer deselects the previous selection. The above code works with a simple input button, though...

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
PhiLho
  • 40,535
  • 6
  • 96
  • 134
  • 1
    8 year old post, I know. But anyway... maybe you could've tried: on your button click call $('').focus(), and then call ShowSelection() that gets the part from the active element? – Krishnan May 21 '14 at 09:10
  • 1
    This can be done [a lot more simply](http://stackoverflow.com/a/32397146/1269037). – Dan Dascalescu Sep 04 '15 at 11:38
18

Here's a much simpler solution, based on the fact that text selection occurs on mouseup, so we add an event listener for that:

document.querySelector('textarea').addEventListener('mouseup', function () {
  window.mySelection = this.value.substring(this.selectionStart, this.selectionEnd)
  // window.getSelection().toString();
});
<textarea>
  Select some text
</textarea>
<a href="#" onclick=alert(mySelection);>Click here to display the selected text</a>

This works in all browsers.

If you also want to handle selection via the keyboard, add another event listener for keyup, with the same code.

If it weren't for this Firefox bug filed back in 2001 (yes, 14 years ago), we could replace the value assigned to window.mySelection with window.getSelection().toString(), which works in IE9+ and all modern browsers, and also gets the selection made in non-textarea parts of the DOM.

Community
  • 1
  • 1
Dan Dascalescu
  • 143,271
  • 52
  • 317
  • 404
  • So you criticize solutions given seven years ago, without indicating your won't work in IE < 9*... :-) OK, that's good to update the topic with a modern solution, but don't forget some people care for older browsers. * https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection – PhiLho Sep 04 '15 at 14:11
  • @PhiLho: It's mind-boggling that it doesn't work in FF - the bug for that was filed 14 years ago. Updated answer. – Dan Dascalescu Sep 05 '15 at 19:30
  • 1
    This solution works well however id the cursor goes out of the textarea 'box' the event will not fire. You must add the following code to make it work in that case: document.querySelector('textarea').addEventListener('mouseleave', function () { window.mySelection = this.value.substring(this.selectionStart, this.selectionEnd); }); The event will then also fire when you leave the textarea, therefore keeping your selection. – Darxtar Oct 09 '16 at 00:15
  • Mouse? Does it work if the keyboard is used for selection? Can you address that in your answer? – Peter Mortensen May 09 '22 at 02:39
4

function disp() {
  var text = document.getElementById("text");
  var t = text.value.substr(text.selectionStart, text.selectionEnd - text.selectionStart);
  alert(t);
}
<TEXTAREA id="text">Hello, How are You?</TEXTAREA><BR>
<INPUT type="button" onclick="disp()" value="Select text and click here" />
Dan Dascalescu
  • 143,271
  • 52
  • 317
  • 404
prat3ik-patel
  • 1,205
  • 9
  • 5
  • 1
    This happens to work, but if you had more complicated code in `disp()`, by the time that code got the selection from the textarea (e.g. constructing a [selection-menu](https://github.com/iDoRecall/selection-menu), the browser might have cleared it because the `click` event occurring on the button means the textarea receives a [blur](https://developer.mozilla.org/en-US/docs/Web/Events/blur) event, which clears the selection. [My answer](http://stackoverflow.com/a/32397146/1269037) addresses that by saving the selection in a variable when it occurs. – Dan Dascalescu Sep 05 '15 at 19:49
2

For Opera, Firefox and Safari, you can use the following function:

function getTextFieldSelection(textField) {
    return textField.value.substring(textField.selectionStart, textField.selectionEnd);
}

Then, you just pass a reference to a text field element (like a textarea or input element) to the function:

alert(getTextFieldSelection(document.getElementsByTagName("textarea")[0]));

Or, if you want <textarea> and <input> to have a getSelection() function of their own:

HTMLTextAreaElement.prototype.getSelection = HTMLInputElement.prototype.getSelection = function() {
    var ss = this.selectionStart;
    var se = this.selectionEnd;
    if (typeof ss === "number" && typeof se === "number") {
        return this.value.substring(this.selectionStart, this.selectionEnd);
    }
    return "";
};

Then, you'd just do:

alert(document.getElementsByTagName("textarea")[0].getSelection());
alert(document.getElementsByTagName("input")[0].getSelection());

for example.

Shadow2531
  • 11,980
  • 5
  • 35
  • 48
1

I am a big fan of jQuery-textrange.

Below is a very small, self-contained, example. Download jquery-textrange.js and copy it to the same folder.

<!doctype html>
<html>

<head>
    <meta charset="UTF-8">
    <title>jquery-textrange</title>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script src="jquery-textrange.js"></script>

    <script>
        /* Run on document load */
        $(document).ready(function() {
            /* Run on any change of 'textarea' **/
            $('#textareaId').bind('updateInfo keyup mousedown mousemove mouseup', function() {

                /* The magic is on this line **/
                var range = $(this).textrange();

                /* Stuff into selectedId. I wanted to
                   store this is a input field so it
                   can be submitted in a form. */
                $('#selectedId').val(range.text);
            });
        });
    </script>
</head>

<body>
    The smallest example possible using
    <a href="https://github.com/dwieeb/jquery-textrange">
       jquery-textrange
    </a><br/>
    <textarea id="textareaId">Some random content.</textarea><br/>
    <input type="text" id="selectedId"></input>

</body>

</html>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
fishjd
  • 1,617
  • 1
  • 18
  • 31
0
// jQuery
var textarea = $('#post-content');
var selectionStart = textarea.prop('selectionStart');
var selectionEnd = textarea.prop('selectionEnd');
var selection = (textarea.val()).substring(selectionStart, selectionEnd);

// JavaScript
var textarea = document.getElementById("post-content");
var selection = (textarea.value).substring(textarea.selectionStart, textarea.selectionEnd);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Optimaz Prime
  • 857
  • 10
  • 11