Thursday, September 4, 2025
HomeLanguagesJavascriptHow to place cursor position at end of text in text input...

How to place cursor position at end of text in text input field using JavaScript ?

In this article, we are going to learn about how to place the cursor at the end of the text in a text input element using JavaScript

At first, we are going to create a text input box where some value will be given and a button to place the cursor at the end. We can place the cursor at the end of the text in a text input element by using different JavaScript functions.

Approach: The JavaScript functions that are used are:

  • HTMLInputElement.setSelectionRange(): The HTMLInputElement.setSelectionRange() is a method that sets the start and end positions of the current text selection in an <input> or <textarea> element.
  • Element.createTextRange(): It provides us with a selected text range in an input form. A caret is also known as a text cursor which is an indicator on the screen to indicate where the text is to be inserted.
  • TextRange.collapse(): It helps to move the caret to the beginning or end of the current range.
  • TextRange.moveEnd(): It helps to move the end of the range by a specified number of units.
  • TextRange.moveStart(): It moves the start of the range by a specified number of units.

Example: This example shows the above-explained approach.

HTML




<!DOCTYPE html>
<html>
<body>
    <center>
        <h1>Put Cursor at End of Input</h1>
 
        <!-- Creating an Input Text Box and
            the button to move cursor at the
            end of the text-->
        <input id="idText" type="text" size="70"
            value="Cursor at the End">
 
        <button onclick="PosEnd(idText);">
            Put Cursor at end of Text
        </button>
    </center>
    <script>
        /* Creating a function called PosEnd
         in JavaScript to place the cursor
         at the end */
        function PosEnd(end) {
            var len = end.value.length;
             
            // Mostly for Web Browsers
            if (end.setSelectionRange) {
                end.focus();
                end.setSelectionRange(len, len);
            } else if (end.createTextRange) {
                var t = end.createTextRange();
                t.collapse(true);
                t.moveEnd('character', len);
                t.moveStart('character', len);
                t.select();
            }
        }
    </script>
</body>
</html>


Output:

 

RELATED ARTICLES

Most Popular

Dominic
32264 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6629 POSTS0 COMMENTS
Nicole Veronica
11799 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11859 POSTS0 COMMENTS
Shaida Kate Naidoo
6749 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6698 POSTS0 COMMENTS
Umr Jansen
6718 POSTS0 COMMENTS