Tanvi Patel Tanvi Patel - 25 days ago 12
Javascript Question

set cursor position in textBox javascript

I am trying to add new line to textBox and update textBox value with new line character in JavaScript using following code:

ele.value = ele.value + "\n";

ele.focus();

// To update cursor position to recently added character in textBox
ele.setSelectionRange(value.length, value.length);


Above code updates textBox value but doesn't update cursor position to new line.

(Though it updates cursor position when I click outside of textBox and again click inside textBox, but not when textBox is already being edited by user.)

Answer

function insertNewlineAndFocus() {
  let textarea = document.getElementById("unicorn");
  textarea.value = textarea.value + "\n";
  textarea.focus();
}
button {
  display: block;
  margin: 10px;
}
textarea {
  min-width: 50%;
  min-height: 100px;
  margin: 10px;
}
<button onclick="insertNewlineAndFocus()">do it!</button>
<textarea id="unicorn">the most phenomenal text, really, its the best</textarea>