Home >Web Front-end >JS Tutorial >How to Insert Text at the Cursor Position in a Text Area using JavaScript?
Inserting Text at Cursor Position with Javascript/jQuery
In web development, adding text where the cursor is positioned can enhance user experience. One scenario includes allowing users to seamlessly insert predefined text into a textbox upon clicking a link.
Inserting Text at Cursor Position
To insert text at the cursor position, we can utilize the following JavaScript function:
function insertAtCaret(areaId, text) { // Get the textarea element var txtarea = document.getElementById(areaId); // Check if the element exists if (!txtarea) { return; } // Determine the browser type (Internet Explorer or others) var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ? "ff" : (document.selection ? "ie" : false)); // Calculate the cursor position var strPos = 0; if (br == "ie") { txtarea.focus(); var range = document.selection.createRange(); range.moveStart('character', -txtarea.value.length); strPos = range.text.length; } else if (br == "ff") { strPos = txtarea.selectionStart; } // Create a string that consists of the text before, after, and the inserted text var front = (txtarea.value).substring(0, strPos); var back = (txtarea.value).substring(strPos, txtarea.value.length); txtarea.value = front + text + back; // Reset the cursor position after inserting the text strPos = strPos + text.length; if (br == "ie") { txtarea.focus(); var ieRange = document.selection.createRange(); ieRange.moveStart('character', -txtarea.value.length); ieRange.moveStart('character', strPos); ieRange.moveEnd('character', 0); ieRange.select(); } else if (br == "ff") { txtarea.selectionStart = strPos; txtarea.selectionEnd = strPos; txtarea.focus(); } }
Example Usage
The following HTML and JavaScript code demonstrates how to use the insertAtCaret() function:
<textarea>
The above is the detailed content of How to Insert Text at the Cursor Position in a Text Area using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!