Friday, July 17, 2009

JavaScript Finding Your Place in a Textbox

Finding the location of the cursor in a texbox is straight forward if you only want to support one browser. There are various reasons why you will want to know the location of the cursor in a textbox. For me, it was a request to create one of those auto completion dropdown lists that suggest the word you are trying to type. While simple enough to do, the twist in the requirement was to prompt the user for each word that was entered followed by a comma. That is to say make a suggestion for Aspley if the user types "Asp" and also make a suggestion for Toowomba if the text string is "Aspley, Too". In-other-words, I had to know the location of the cursor in order to suggest the correct city name in Queensland, Australia.

Here is my solutions:





function getposition(txt1)
{
try //ie
{
var position=0;
var currentRange=document.selection.createRange();
var workRange=currentRange.duplicate();

txt1.select();

var allRange=document.selection.createRange();

while(workRange.compareEndPoints("StartToStart",allRange)>0)
{
workRange.moveStart("character",-1);
position++;
}

currentRange.select();
return position;
}
catch(Err) //firefox
{
return txt1.selectionStart;
}
}

Usage:
var cursorPosition = GetPosition(document.getElementById('<%= txtTextBoxNameInASPdotNET.ClientID %>'));



Note: To get an element's id in JavaScript from an ASP.net control use the following javascript and inline asp.net code:

var txt1=document.getElementById('<%= [asp.net control name].ClientID %>');




I found the following solution here:

No comments: