put cursor at end of text input's value

后端 未结 5 2045
没有蜡笔的小新
没有蜡笔的小新 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 07:58

    Use this, its nice work for me...

    <input type="text" name="txt" value="value text" autofocus="" onfocus="this.setSelectionRange(this.value.length,this.value.length);">
    

    OR add this line to your input element

    onfocus="this.setSelectionRange(this.value.length,this.value.length);"
    
    0 讨论(0)
  • 2021-02-02 07:58

    You can add this parameter to your text input field:

    onmouseover="this.setSelectionRange(this.value.length,this.value.length);"
    onfocus="this.setSelectionRange(this.value.length,this.value.length);"
    

    NB: Works well under Chromium in 2017.

    0 讨论(0)
  • 2021-02-02 08:05

    Upgrade to @harsha's answer

    I found that to make solution work with Firefox, we need temporary reset value to "not-equal of value", then set it back

    <input type="text" autofocus value="value text" onfocus="var temp_value=this.value; this.value=''; this.value=temp_value" />

    0 讨论(0)
  • 2021-02-02 08:15

    This works for me

    <input type="text" autofocus value="value text" onfocus="this.value = this.value;"/>

    0 讨论(0)
  • 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);
        });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    
    <input type="text" id="txt1" value="Lorem" style="width:400px;" />

    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();
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    
    <input id="search" type="text" value="mycurrtext" size="30" name="search" />

    This question already exist on stackoverflow:

    Reference1

    Reference2

    0 讨论(0)
提交回复
热议问题