How to set the cursor position at the end of a string in a text field using jQuery?

谁说我不能喝 提交于 2021-02-07 10:37:17

问题


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();

回答1:


$('#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();
    }
});



回答2:


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");
});



回答3:


Use below code:

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

Hope this help for you



来源:https://stackoverflow.com/questions/7368750/how-to-set-the-cursor-position-at-the-end-of-a-string-in-a-text-field-using-jque

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!