Welcome to WebmasterWorld Guest from

Forum Moderators: open

Message Too Old, No Replies

How do I use javascript to insert text at the current cursor position?

How do I use javascript to insert text at the current cursor position?

6:44 pm on Oct 28, 2005 (gmt 0)

Junior Member

10+ Year Member

joined:June 7, 2005
votes: 0

I am making a webpage that uses hotkeys (alt+[letter]) to insert accents and special characters. Got the hotkey part to work fine, but I can't seem to find any codebits for inserting text into the current position of the current textbox. I can append to a specific field, but thats not what I want. If anyone has any suggestions that would be great.
5:12 pm on Nov 4, 2005 (gmt 0)

Full Member

10+ Year Member

joined:Aug 3, 2005
votes: 0

I think you have to use the createRange()

I tried to write a text editor a wjile ago used this to find where the cursor was on the page, from there you could work what your cursor had selected or where it was at any time and then work out how long the value of the text box or table cell is and insert the relevant value into there.

Have a look at this page, it helped me.


here is a function i made to insert tags into relevant parts of the page.

function insertTag(what_type)
var totalString; //store original string so that we can manipulated
var selectedString; //the selected string
var totalLength; //total length of the string
var selectedLength; //length of the selected area
var indexStart; //index of the string selected
var indexFinished; //last index of the string selected
var firstTextValue; //the first part of the string before index
var lastTextValue; //the last part of the string after index

totalString = document.all("BodySpan").innerText;
selectedString = document.selection.createRange().text;
totalLength = document.all("BodySpan").innerText.length;
selectedLength = document.selection.createRange().text.length;
indexStart = totalString.indexOf(selectedString);
indexFinished = indexStart + selectedLength;
firstTextValue = totalString.substring(0, indexStart);
lastTextValue = totalString.substring(indexFinished, totalLength);
if(what_type == 'pink')
selectedString = "<span class="+String.fromCharCode(34)+"style1"+String.fromCharCode(34)+">"+selectedString+"</span>";
document.all("BodySpan").innerText = firstTextValue + selectedString + lastTextValue;
document.form1.text1.value = firstTextValue + selectedString + lastTextValue;
//document.form1.text1.value = document.all("BodySpan").innerText;




Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members