admin管理员组文章数量:1199522
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.)
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.)
Share Improve this question asked Nov 13, 2016 at 21:27 Tanvi PatelTanvi Patel 1,3273 gold badges12 silver badges18 bronze badges 1- which browser? my answer below works as expected in chrome, but not safari. – skav Commented Nov 13, 2016 at 21:44
2 Answers
Reset to default 13This 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.
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>
本文标签: htmlset cursor position in textBox javascriptStack Overflow
版权声明:本文标题:html - set cursor position in textBox javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738544275a2096108.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论