web-dev-qa-db-ja.com

textBox javascriptでカーソル位置を設定する

次のコードを使用して、JavaScriptでtextBoxに新しい行を追加し、textBoxの値を改行文字で更新しようとしています。

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

ele.focus();

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

上記のコードはtextBox値を更新しますが、カーソル位置を新しい行に更新しません。

(textBoxの外側をクリックして再度textBoxをクリックするとカーソル位置が更新されますが、textBoxが既にユーザーによって編集されている場合は更新されません。)

7
Tanvi Patel

これはFirefoxでも機能するはずです。

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の例

フォーカスしてからテキストを選択しています。

7
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>
7
skav