What do selectionStart and selectionEnd signify for textarea?
Asked Answered
M

5

8

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?

Multiplier answered 22/2, 2015 at 21:6 Comment(0)
S
12

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.

Shirr answered 22/2, 2015 at 22:2 Comment(0)
R
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.

Ruthanneruthe answered 22/2, 2015 at 21:29 Comment(2)
Thanks Marc, i understand selectionStart and selectionEnd well. but document.selection is undefined in firefox too. what this do ??Characterization
@Characterization There's no selection property on the document object. selection in the context of the web is an object that can only be retrieve via calling window.getSelection() or document.getSelection(). However, calling these methods on textarea will return undefined in Firefox.Underhand
T
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.

Tzong answered 22/2, 2015 at 22:14 Comment(1)
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.Narcoma
U
0

From the perspective of the web, input elements will always have selectionStart and selectionEnd properties. They refer to the start and end positions of the current text selection respectively. If nothing is selected,the start and end positions are treated as 0.

For end users, selection is commonly understood as clicking and dragging over a part of the text, which leads to the confusion.

There are exceptions: When the input is not of type text, search, url, tel and password, selectionStart and selectionEd will be undefined.

That's why Typescript users have experienced this problem, where Typescript complains that selectionStart may be null.

Underhand answered 7/12, 2023 at 6:50 Comment(0)
H
0

selectionStart and selectionEnd are properties of an input or textarea element that contain the index of the first and last selected characters respectively. When no text is explicitly selected, the selectionStart and selectionEnd properties are still defined, but they represent the cursor position in the text.

In the provided code, when the Enter key is pressed and the ctrlKey is held down, the selectionStart and selectionEnd properties are used to determine the current cursor position. Then, the textarea value is manipulated to insert a newline character at the cursor position.

If no text is selected and the cursor is at the end of the text, selectionStart and selectionEnd will both be equal to the length of the text. If no text is selected and the cursor is at the beginning of the text, selectionStart and selectionEnd will both be equal to 0.

This is why both properties always have some value even when the text is not explicitly selected.

Holarctic answered 7/12, 2023 at 7:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.