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