2

Possible Duplicate:
Use JavaScript to place cursor at end of text in text input element

I have an input field which only takes numbers. Can any one please let me know how to place the cursor only at the end of this text box when clicked on the field.

This is for an mobile optimized site and hence when user clicks on this input form, the cursor should be placed only at the end and the user can delete the number with a back arrow on their phone.

Thanks in advance!

Community
  • 1
  • 1
Srinivas
  • 135
  • 4
  • 9
  • Usually if you just click at the end of the field your browser will put the cursor at the end of the text. Is the field too small that not all the numbers fit on the screen or something? I find it pretty easy to select where in the field I want my cursor to be at using my thumb... – animuson Aug 11 '11 at 21:58
  • There is only one number and I want to freeze the cursor to the left since if somebody taps on the box to the left of a number on a phone, the user should again move the cursor to the right and press the back button. Hope it explains. Let me try with the above link mentioned and get back. Thanks! – Srinivas Aug 11 '11 at 22:11

3 Answers3

2

You can try an onclick or onfocus event, which reads the value of the field, then writes it back. When adjusting the text in an active text field, the cursor jumps at the end.

$("#yourtextfield").click(function() {
    var v = $(this).val();
    $(this).val(v);
});

You can try it here: http://jsfiddle.net/inti/uYzVP/

aorcsik
  • 15,271
  • 5
  • 39
  • 49
  • It's working perfectly on the link you provided. I did try on creating a simple html and including the jquery library but it isn't working on any browser. Am I missing something? This is the solution I wanted. Thanks! – Srinivas Aug 11 '11 at 22:28
  • Works awesome. I had forgot to include document ready function. – Srinivas Aug 11 '11 at 22:52
0

This is similar to this question: jQuery Set Cursor Position in Text Area

All you do different from this solution is pass in the length of the textfield to the function instead of a hardcoded value.

Community
  • 1
  • 1
BumbleB2na
  • 10,723
  • 6
  • 28
  • 30
0

Something that works with firefox, chrome, android browser, safari on Mac iPad and on the iphone emulator is to use

element.setSelectionRange(element.value.length, element.value.length);
6502
  • 112,025
  • 15
  • 165
  • 265