Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofocus With Cursor On End Of Textbox

I want to put autofocus on a html textbox such that the cursor points to the end of some text already present in the textbox. I know what the autofocus attribute does. And I have also seen put cursor at end of text input's value which answers how to put cursor at the end, But the textbox is not autofocussed upon page reload. How can I do both - autofocus the textbox upon page reload and put cursor to end of text ?

Code : 

 <textarea id="txtArea" style="width:106%; height:100px" align="center" name="task1" onkeypress="onTestChange();" onfocus="this.value = this.value;" autofocus ><?php echo $_GET["task"];?></textarea>

I want to put Cursor after the text echoed. It is not the value of the textarea.

Also the textbox I referred to is Textarea.

like image 599
Stack Man Avatar asked Nov 07 '14 05:11

Stack Man


People also ask

How do I keep my cursor in a TextBox?

To position the cursor at the end of the contents of a TextBox control, call the Select method and specify the selection start position equal to the length of the text content, and a selection length of 0.

How do you move the cursor to the end?

To move the cursor to the end of an input field: Use the setSelectionRange() method to set the current text selection position to the end of the input field. Call the focus() method on the input element. The focus method will move the cursor to the end of the input element's value.

How do you move the cursor to the end of Contenteditable entity?

selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range range. collapse(false);//collapse the range to the end point. false means collapse to end rather than the start selection = window. getSelection();//get the selection object (allows you to change selection) selection.


2 Answers

Please use this code and run in your browser

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

});
<input type="text" id="test" autofocus value="value text" />
like image 186
Avinash Antala Avatar answered Oct 01 '22 01:10

Avinash Antala


try to run this simple code and see u will notice that first text box will be focused and not the second

<input type="text" autofocus value="value text" onfocus="this.value = this.value;"/>
<input type="text" autofocus value="value text" onfocus="this.value = this.value;"/>
like image 37
kki3908050 Avatar answered Oct 01 '22 03:10

kki3908050