Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.)

like image 436
Tanvi Patel Avatar asked Nov 13 '16 21:11

Tanvi Patel


People also ask

How do you get the cursor position in a textbox in HTML?

Syntax: // will give the current position of the cursor document. getElementById("id"). selectionStart; // will get the value of the text area let x= $('#text1').

What is caret position in Javascript?

The CaretPosition interface represents the caret position, an indicator for the text insertion point. You can get a CaretPosition using the Document. caretPositionFromPoint() method.

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

createTextRange();//Create a range (a range is a like the selection but invisible) range. moveToElementText(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 range.


2 Answers

This should work in Firefox as well:

HTML:

<!DOCTYPE html>
  <html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
  </head>
  <body>
    <textarea id="myText" rows="4" cols="50" onkeypress="">The rain in Spain falls mainly on the plains.</textarea>
    <br>
    <button onclick="updateText()">Update</button>
  </body>
</html>

Javascript:

 function updateText(e) {
 var ele = document.getElementById('myText');
 var newVal = 'Old McDonald had a farm.\n';

 ele.value = newVal;
 ele.focus();

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

JS Bin example

I'm selecting the text after focusing.

like image 191
Chris Ochsenreither Avatar answered Sep 23 '22 12:09

Chris Ochsenreither


function insertNewlineAndFocus() {
  let textarea = document.getElementById("unicorn");
  textarea.value = textarea.value + "\n";
  textarea.setSelectionRange(textarea.value.length, textarea.value.length);
  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>
like image 32
skav Avatar answered Sep 25 '22 12:09

skav