There is a javascript button that if it's pressed, it inserts a string. Then after pressing a button, focus will back to textfield. However, with my code, always focus goes back to end of the string, not where it was.
For example now focus is between 3 and 4.
and after pressing "ā", focus goes to after 7.
But I want the focus go to between "ā" and 4.
Here is my code
<script>
function addTF(str)
{
var area = document.getElementById('pronounce');
area.value = area.value.substr(0, area.selectionStart)
+ str
+ area.value.substr(area.selectionStart);
area.focus();
}
</script>
<input type="text" id="pronounce" name="pronounce">
<input type="button" value="ā" onClick="addTF(this.value)">
So how can I achieve this? Thank you.
You can set the selectionStart
and selectionEnd
of the text field to restore the previous caret position:
var addTF;
window.addEventListener('load', () => {
var area = document.getElementById('pronounce');
var lastPos = 0;
area.addEventListener('change', () => lastPos = area.selectionStart);
area.addEventListener('click', () => lastPos = area.selectionStart);
addTF = function(str) {
area.value = area.value.substr(0, area.selectionStart) + str + area.value.substr(area.selectionStart);
lastPos++;
area.selectionStart = lastPos;
area.selectionEnd = lastPos;
area.focus();
}
});
<input type="text" id="pronounce" name="pronounce">
<input type="button" value="ā" onClick="addTF(this.value)">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With