After a postback, I have managed to focus on the textbox using the following code:
ScriptManager.RegisterStartupScript(textBox, textBox.GetType(), "selectAndFocus", "$get('" + textBox.ClientID + "').focus();", true);
However, this code sets the cursor position at the beginning of the textbox rather than after the last typed character. To address this issue, I attempted the following code:
textBox.Attributes.Add("onfocus", "$get('" + textBox.ClientID + "').value = $get('" + textBox.ClientID + "').value;");
Unfortunately, this solution did not work for me and resulted in the same outcome as before. Is there any other way to solve this problem?
I have gone through numerous resources, with this one appearing to be the most promising solution, but I have struggled to implement it successfully.
UPDATE: I forgot to mention that the textbox is located within an updatepanel.
UPDATE2, Here is the attempted solution:
string setCaretTo = @"function setCaretTo(obj, pos) {
if(obj.createTextRange) {
/* Create a TextRange, set the internal pointer to
a specified position and show the cursor at this
position
*/
var range = obj.createTextRange();
range.move('character', pos);
range.select();
} else if(obj.selectionStart) {
/* Gecko is a little bit shorter on that. Simply
focus the element and set the selection to a
specified position
*/
obj.focus();
obj.setSelectionRange(pos, pos);
}
}";
ScriptManager.RegisterClientScriptBlock(//anotherunrelated script);
ScriptManager.RegisterClientScriptBlock(textBox, textBox.GetType(), "MyScript", setCaretTo, true);
ScriptManager.RegisterStartupScript(textBox, textBox.GetType(), "MyStartupScript", "window.onload = function() {obj = window.document.getElementById('"+textBox.ClientID+"');setCaretTo(obj, obj.getAttribute('value').length);}", true);`