The function that moves the cursor of an input element to the end in jQuery is .focus(). But sometimes, this won’t work even if you replace it with [0].click(). It’ll maybe work on input fields properly, but won’t properly at all in text areas. Mostly it won’t work, if you are calling the .focus() function inside an event listener function.
To solve this you can use 2 other methods if the first one don’t work. It’s pretty simple and I don’t know why it works. I found this solution on a Stack Overflow question and the one who answered doesn’t know why it works. Here is a list of the events that happens when an element is clicked :
- mousedown
- focus
- mouseup
- click
If you are calling mousedown on an element, you won’t be able to focus that element in it’s callback. So use mouseup or click for listening events to focus an element.
Let’s get back on the topic. As I said before, there are 3 solutions. If 1 didn’t work move on the Plan B (2) or Plan C (3).
Solution 1
Focus before appending the value :
$("textarea").focus().val("How Did This Happen ?");
Solution 2
Add value first, then focus and add value again (original solution by Stack Overflow user) :
$("textarea").val("Two Values").focus().val("Two Values");
Solution 3
Focus, clear value, then revert to original value :
$("textarea").focus().val("").val("Original Value");
If you have any other methods to do this confusing task, please share it.