To get cursor position (in characters) within a text Input field with JavaScript, we use the selectionStart
method.
For instance, we write
<input type="text" id="t1" value="abcd" />
<button onclick="onClick(document.getElementById('t1'))">check position</button>
to add an input and a button.
Then button calls the onClick
function when we click on the element with the input as its argument.
Next we write
function onClick(el) {
const val = el.value;
console.log(val.slice(0, el.selectionStart).length);
}
to define the onClick
function.
In it, we get the input’s value with el.value
.
And then we get the cursor position with el.selectionStart
.
We call slice
to get the part of the val
string between index 0 and el.selectionStart - 1
.