7

I came across following code snippet to insert enter into the the text in a textarea where ctrl + enter is pressed.

$("#txtChatMessage").keydown(MessageTextOnKeyEnter);
function MessageTextOnKeyEnter(e) {
    console.log(this.selectionEnd);
    if (e.keyCode == 13) {
        if (e.ctrlKey) {
            var val = this.value;
            if (typeof this.selectionStart == "number" && typeof this.selectionEnd == "number") {
                var start = this.selectionStart;

                this.value = val.slice(0, start) + "\n" + val.slice(this.selectionEnd);
                this.selectionStart = this.selectionEnd = start + 1;
            } else if (document.selection && document.selection.createRange) {
                this.focus();
                var range = document.selection.createRange();
                range.text = "\r\n";
                range.collapse(false);
                range.select();
            }
        }
        return false;
    }
}

What I don't understand is what do selectionStart and selectionEnd mean here ? According to documentation that I read, selectionStart-End contain the start-end of selected text in the input element. However, here no text is explicitly selected. On doing console.log I could see that both these properties always have some value even when the text is not selected. Why is that?

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
vjain27
  • 3,514
  • 9
  • 41
  • 60

3 Answers3

10

selectionStart specifies the index of the selection/highlighted text within the <textarea>. Similarly, selectionEnd specifies the index where the selection ends. Initially, they are set to 0, and if the <textarea> is focused but no text is selected, the selectionStart and selectionEnd values will be the same, and reflect the position of the caret within the value of the <textarea>. On un-focus or blur of the <textarea>, they will remain at the last value that they were set to before the blur event.

andrewgu
  • 1,562
  • 14
  • 23
3

Here's a fiddle you can play with: http://jsfiddle.net/5vd8pxct/

The if block in question appears to handle cross-browser compatibility. document.selection is for IE. selectionStart and selectionEnd seem to work elsewhere. I don't have IE on my machine to experiment with it, and I'm using Chrome. It appears from my fiddle that the default start/end are 0 when the page loads. If you click into/select in the box, the start end will be as expected. If you click outside the box, the positions within the box are remembered.

document.selection is undefined in Chrome.

Marc
  • 11,403
  • 2
  • 35
  • 45
  • Thanks Marc, i understand selectionStart and selectionEnd well. but document.selection is undefined in firefox too. what this do ?? – Rupal Feb 17 '18 at 06:30
1

Your code does not work. You mix regular JavaScript and JQuery. I would suggest to start with plain JavaScript. Generally, in JavaScript this is a reference to the object on which the code will be executed.

Take a look at the following example:

<html>
<head>
    <script type="text/javascript">
        window.addEventListener("load", function () {
            var chat = document.getElementById('txtChatMessage'); // get textarea

            chat.addEventListener('keydown', function (event) { //add listener keydown for textarea

                event = event || window.event;

                if (event.keyCode === 13) {  //return pressed?
                    event.preventDefault();
                    if (this.selectionStart != undefined) {
                        var startPos = this.selectionStart;
                        var endPos = this.selectionEnd;
                        var selectedText = this.value.substring(startPos, endPos);
                        alert("Hello, you've selected " + selectedText);
                    }
                }
                
            })
        });
    </script>
</head>

<body>
    <textarea id="txtChatMessage" cols="40" rows="10"></textarea>
</body>
</html>

At first an event listener "onLoad" has been registered. Within this function we get a reference to the textarea object. On this object a new event listener "onKeyDown" has been registered. Within this function this refers to the textarea (chat) object. With the help of the event object, we can ask for the pressed key event.keyCode === 13. With this (textarea) and its attributes selectionStart and selectionEnd we get the selected text.

seboettg
  • 195
  • 8
  • Little update to the above: when I try out textarea manipulations of this sort, selectionStart equals the character position of the character *immediately preceding* the caret. – David Edwards Dec 05 '18 at 21:32