Reputation: 1608
I need to use an external keyboard to populate some input fields. I need a user to be able to position the cursor to a specific place in the field and the text should continue from that place.
I found a problem with getting a cursor position in the textfield when using selectionStart.
the code below shows the error - instead of adding a digit at the end of textfield, it's added to the beginning as inp.selectionStart returns 0;
Interestingly, I've discovered that if I remove the line inp.focus(); then it's working better when adding digits to the end of the value but when I click on a specific place inside the string, it's working fine once and then braking again and jumps to 0.
let inp;
let btn;
let dig = 0;
document.addEventListener("DOMContentLoaded", init);
function init() {
inp = document.getElementById('inp');
btn = document.getElementById('btn');
btn.addEventListener("click", add_digit);
inp.focus();
}
function add_digit() {
const caretPos = inp.selectionStart;
console.log('caretPos', caretPos)
inp.value = inp.value.substring(0, caretPos) + (++dig%10) + inp.value.substring(caretPos);
inp.setSelectionRange(caretPos+1, caretPos+1)
}
<input id="inp" />
<button id="btn">add digit</button>
Upvotes: 0
Views: 37
Reputation: 1608
I found that adding inp.focus() to the end of add_digit() function helped achieve the functionality in the snippet here.
let inp;
let btn;
let dig = 0;
document.addEventListener("DOMContentLoaded", init);
function init() {
inp = document.getElementById('inp');
btn = document.getElementById('btn');
btn.addEventListener("click", add_digit);
inp.focus();
}
function add_digit() {
const caretPos = inp.selectionStart;
console.log('caretPos', caretPos)
inp.value = inp.value.substring(0, caretPos) + (++dig%10) + inp.value.substring(caretPos);
inp.setSelectionRange(caretPos+1, caretPos+1);
inp.focus();
}
<input id="inp" />
<button id="btn">add digit</button>
Upvotes: 0