I am using this code to move the cursor at the end of text area on button click. The code works and i can see the cursor at the end but text area loses focus automatically on button click. In other words, when I click the button the cursor just pops out once at the end and then text area loses focus.
Below is the code i am using:
$.fn.selectRange = function (start, end) {
return this.each(function () {
if (this.setSelectionRange) {
this.focus();
this.setSelectionRange(start, end);
} else if (this.createTextRange) {
var range = this.createTextRange();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', start);
this.focus();
range.select();
}
});
};
function setSelectionRange() {
var el=document.getElementById('txt_comments');
$(el).selectRange(el.innerHTML.length, el.innerHTML.length);
}
<asp:Button ID="editcomments" runat="server" Text="Edit"
Height="36px" style=" padding:5px; margin-top: 0px" Width="72px"
OnClientClick="setSelectionRange();" />
I’m unfamiliar with .NET, however triggering focus on another element from a click event is problematic because the click event doesn’t necessarily fire after the element has itself finished with its own focus.
What’s happening is the button is getting focus (you click on it), then your code gives focus to the text box, and then focus returns to the button to finish the click event.
You can try two things – first, try
return false;at the end of yoursetSelectionRange()function – it may prevent focus from going back to the button. If that doesn’t work, try registering your function on the mouseup event instead of the click event. That may be late enough for focus to be given up so you can put it on another element.