1

I am using jQuery 1.6 and I have a text field for which I would like the cursor to be positioned at the end of the string\text after the field receives focus. Is there a trivial or easy to do this?

At this time I am using the following code:

$jQ('#css_id_value').focus(function(){
    this.select();
});
$jQ('css_id_value').focus();
Matt Chan
  • 618
  • 14
  • 25
user502052
  • 14,458
  • 30
  • 105
  • 184
  • Checkout this post: http://stackoverflow.com/questions/511088/use-javascript-to-place-cursor-at-end-of-text-in-text-input-element – Kevin Bowersox Sep 10 '11 at 00:25

3 Answers3

3
$('#foo').focus(function() {
    if (this.setSelectionRange) {
        this.setSelectionRange(this.value.length, this.value.length);
    } else if (this.createTextRange) {
        // IE
        var range = this.createTextRange();
        range.collapse(true);
        range.moveStart('character', this.value.length);
        range.moveEnd('character', this.value.length);
        range.select();
    }
});
FtDRbwLXw6
  • 26,504
  • 13
  • 65
  • 104
0

http://jsfiddle.net/hn8EY/

$("input").mouseup(function(){
    this.selectionStart = this.value.length;
    this.selectionEnd = this.value.length;
});

that should do it.

and alternatively (because I have no clue what your after here :P)

$("input").mouseup(function(){
    if($(this).not(".c").length) {
        this.selectionStart = this.value.length;
        this.selectionEnd = this.value.length;
        $(this).addClass("c");
    }
}).blur(function(){
    $(this).removeClass("c");
});
Joseph Marikle
  • 72,900
  • 16
  • 109
  • 126
-1

Use below code:

var FieldInput = $('#fieldName');
var FldLength= FieldInput.val().length;
FieldInput.focus();
FieldInput[0].setSelectionRange(FldLength, FldLength);

Hope this help for you

harsh4u
  • 2,450
  • 3
  • 22
  • 39