How to set the cursor position at the end of a string in a text field using jQuery?
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 us开发者_C百科ing the following code:
$jQ('#css_id_value').focus(function(){
this.select();
});
$jQ('css_id_value').focus();
$('#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();
}
});
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");
});
Use below code:
var FieldInput = $('#fieldName');
var FldLength= FieldInput.val().length;
FieldInput.focus();
FieldInput[0].setSelectionRange(FldLength, FldLength);
Hope this help for you
精彩评论