put cursor at end of text input's value

后端 未结 5 2044
没有蜡笔的小新
没有蜡笔的小新 2021-02-02 07:37

So, currently I have a text-input-field with a value that is also autofocused.

On page load, the value is selected / highlighted. Is there a way I can put the cursor at

5条回答
  •  不知归路
    2021-02-02 08:23

    Use Jquery for this:

    $(function() {
          var input = $("#txt1");
        var len = input.val().length;
        input[0].focus();
        input[0].setSelectionRange(len, len);
        });
    
    
    

    But some browsers don't support enter code here property, in which case use this:

    $(document).ready(function(){
        $("#search").focus(function(){
            if (this.setSelectionRange)
            {
            var len = $(this).val().length;
            this.setSelectionRange(len, len);
            }
            else
            {
            $(this).val($(this).val());
            }
       
    });
    
    $("#search").focus();
    });
    
    
    

    This question already exist on stackoverflow:

    Reference1

    Reference2

提交回复
热议问题