0

I have an input field and after a tab or enter keydown event some text is filled into the input field. How do I then make the cursor be at the end of the text that was filled?

This is the html:

<input name="author" type="text" id="author"></input>

This is the javascript:

var authorInput = document.getElementById("author");
authorInput.value = authorName;
authorInput.innerHTML = authorName;

where authorName is a string like "example". Now after setting the innerHTML I want the cursor to be at the end of the text in the input field. How do I do this?

I prefer no jquery but am open to it if it is a much "better" solution.

Here is a jsfiddle example with an attempt at solving it, which does not work. I want the div's click event handler to make the cursor be at the end of the input text when it is done running.

user3494047
  • 1,643
  • 4
  • 31
  • 61
  • You can handle default values and cursor autofocus in the HTML. Don't need javascript. – jakeehoffmann Apr 11 '17 at 18:41
  • I don't think its a duplicate because its not an onfocus event. The input is already focused. I will try it right now though. – user3494047 Apr 11 '17 at 18:50
  • @MikeMcCaughan yes i just tried using onfocus and it did not work. I'm looking through the other javascript solutions to see if that helps – user3494047 Apr 11 '17 at 18:52
  • There are more answers than the accepted answer. For instance, [this answer](http://stackoverflow.com/a/10576409/215552) doesn't mention focus and shows how to set the selection manually. There are also other duplicates, like http://stackoverflow.com/q/19568041/215552, http://stackoverflow.com/q/499126/215552... – Heretic Monkey Apr 11 '17 at 18:54
  • Input tags close themselves, so what you have doesn't make sense. You can't write to the inside of a tag if there isn't an inside. – Waxi Apr 11 '17 at 18:57
  • @Waxi you're right but it doesn't affect anything to have the innerHTML there. I delted it but still the question is the same – user3494047 Apr 11 '17 at 18:59

0 Answers0