Howto Place cursor at beginning of textarea

后端 未结 5 1043
有刺的猬
有刺的猬 2021-02-04 12:46

I\'ve found a couple resources for how to place the cursor in a textarea at the end of the text, but I can\'t sort out a simple way to make it appear at the beginning.

相关标签:
5条回答
  • 2021-02-04 13:10

    Removed the spaces between the tags
    like this:

    <textarea rows="5" cols="50" name="extra"></textarea>
    
    0 讨论(0)
  • 2021-02-04 13:14

    please, use for textarea with scroll after using $(textareaSelector).val(val)

    $(textareaSelector)[0].setSelectionRange(0, 0);
    $(textareaSelector).focus();
    
    0 讨论(0)
  • 2021-02-04 13:23

    The jQuery way:

    $('textarea[name="mytextarea"]').focus().setSelectionRange(0,0);
    
    0 讨论(0)
  • 2021-02-04 13:24

    Pass a reference to your textarea to this JS function.

    function resetCursor(txtElement) { 
        if (txtElement.setSelectionRange) { 
            txtElement.focus(); 
            txtElement.setSelectionRange(0, 0); 
        } else if (txtElement.createTextRange) { 
            var range = txtElement.createTextRange();  
            range.moveStart('character', 0); 
            range.select(); 
        } 
    }
    
    0 讨论(0)
  • 2021-02-04 13:31

    Depending on your needs, a simpler Javascript version is:

    document.querySelector("textarea").focus(); //set the focus - cursor at end
    document.querySelector("textarea").setSelectionRange(0,0); // place cursor at start
    

    You can't just string them together either, to get rid of the double querySelector - not sure why.

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