简体   繁体   中英

How can I focus on the end of textarea value?

Here is my code:

 $('input').on('click', function(){ $('textarea').focus(); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea>this is a test</textarea> <br /> <input type="button" value="focus" /> 

How can I focus on the end of textarea value?


As you can see, currently when you click on the button, you will be focused on the textarea, but at the beginning of its value. All I'm trying to do is focusing at the end of that textarea value.

You can use setSelectionRange(start,end) , the arguments are the starting point and the end point of the selection it is setting. If you set both to the last index of the value string, the cursor will be at the end.

 $('input').on('click', function(){ let l=$("textarea").val().length $('textarea').focus() $('textarea')[0].setSelectionRange(l,l); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea>this is a test</textarea> <br /> <input type="button" value="focus" /> 

You can try the following way:

 $('input').on('click', function(){ var preVal = $('#txtArea').val(); $('#txtArea').val(''); $('#txtArea').focus().val(preVal); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea id="txtArea">this is a test</textarea> <br /> <input type="button" value="focus" /> 

One way to go about it is as follows:

  1. Capture the previous text.
  2. focus.
  3. append ' ' to the previous value.

 $('input').on('click', function(){ var text = $('textarea').val(); $('textarea').focus(); $('textarea').val(text + ' '); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea>this is a test</textarea> <br /> <input type="button" value="focus" /> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM