Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


have cursor start at end of text in input text box

I have a text box with OL. in it and I want the cursor to start right after the dot when the page loads. Does anyone know how to do this?

3 Answers

Chris Shaw
Chris Shaw
26,676 Points

Hi Tommy,

I've created a Pen showing how you can do this, to set the cursor position in modern browsers we can use the setSelectionRange method whereas in browsers such as IE8 we need to use createTextRange due to it's older JavaScript engine.


In a nutshell, what's happening is when the page loads (you may need to use a DOMReady event) the value of the input field #test-input gets used as the cursor position, we use the value because the position is based on whole numbers starting from zero.

When the value get's passed through, the browser will change the default position of zero to the value 7 which is the length of the string in the example code, let me know if you have any questions regarding it.

Happy coding!

Thanks! So if I had a textbox that looked like this:

<INPUT TYPE="TEXT" SIZE=7 style="font-size:16pt;" ID="TO_LOC" 
          NAME="TO_LOC" VALUE="<%= FROM_SUB2 %>.">

and I wanted the cursor right after <%= FROM_SUB2 %>. how would that look? and the <%= FROM_SUB2 %>. changes from OL. to BJR. to BCD. depending on what is happening when the page loads, from the <%= FROM_SUB2 %>.

INPUT TYPE="TEXT" SIZE=7 style="font-size:16pt;" ID="TO_LOC" 
          NAME="TO_LOC" VALUE="<%= FROM_SUB2 %>. 

that what I ment to put down

Chris Shaw
Chris Shaw
26,676 Points

In that case you would only need to change the ID which in the pen is #test-input to your ID which is #TO_LOC.

function setCaretPosition(ctrl, pos) {
  // ...

var input = document.getElementById('TO_LOC');
setCaretPosition(input, input.value.length);

Remember you also need the setCaretPosition function which is in the pen, I've cut out it's body to save space and prevent redundancy.

hmm i really appreciate the help but for some reason I cant get it to work. I copy and pasted the entire javascript code into the webpage, and changed the getElementByID to 'TO_LOC' but when page loads ti doenst go to the text box or anything and when I tab down to it it doesn't go to end of text either.