Reputation: 45
So I want to set the cursor position to the end of the textbox after the page is loaded. I have this code for the JQuery:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="https://rawgit.com/ichord/Caret.js/master/src/jquery.caret.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var textbox = $('#MessagesBox');
textbox.focus();
textbox.caret('pos', textbox.val().length);
});
</script>
<asp:TextBox ID="MessagesBox" runat="server" TextMode="MultiLine"
style="resize:none" ReadOnly="true" Width="300" Height="200"></asp:TextBox>
What am I missing? Do I need to set something in the code-behing as well?
Upvotes: 1
Views: 1548
Reputation: 4655
try this :
$(document).ready(function(){
var el = $("#MessagesBox");
var elemLen = el.value.length;
el.selectionStart = elemLen;
el.selectionEnd = elemLen;
el.focus();
});
Upvotes: 1
Reputation: 5771
Your issue is that the ID of the textbox will not remain MessagesBox since it is a server control. ASP.NET changes it and gives it a Client ID. You will need to use the Client ID or use another attribute to identify the textbox in jquery. You can verify the control's name by using Inspect element from Chrome.
You could use this to identify the control by its Client ID
var textbox = $("#'<%=MessagesBox.ClientID %>'");
Alternatively, you have access to the control's client ID on the server side which can then be used to create and register your script from the server.
Upvotes: 2