Howto Place cursor at beginning of textarea
Asked Answered
R

5

17

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.

I'm prepopulating the textarea with some text and just want to make it easier on the users.

Ramiroramjet answered 26/8, 2009 at 18:18 Comment(0)
O
19

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(); 
    } 
}
Omniscience answered 26/8, 2009 at 18:28 Comment(0)
U
8

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.

Urbanism answered 28/8, 2018 at 6:14 Comment(0)
A
2

The jQuery way:

$('textarea[name="mytextarea"]').focus().setSelectionRange(0,0);
Ashelman answered 15/12, 2019 at 4:12 Comment(1)
This won't work. Should be: $('textarea[name="mytextarea"]').focus().get(0).setSelectionRange(0,0); ... the added get(0) is to expose the DOM element since setSelectionRange() is a DOM method rather than a jQuery one.Quahog
G
0

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

$(textareaSelector)[0].setSelectionRange(0, 0);
$(textareaSelector).focus();
Griffey answered 13/8, 2020 at 4:48 Comment(0)
M
-4

Removed the spaces between the tags
like this:

<textarea rows="5" cols="50" name="extra"></textarea>
Mcmullen answered 4/12, 2016 at 11:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.