0

Is there a way to get the index of a character that is clicked on inside an input field?

For example, in an input field the value: "abc" is put.
and I click on the input field specifically on the "b".
I would like to know that the click was handled on index 1;

I have searched through the mouse event that is fired with an onClick and onFocus but couldn't find anything useful. The closest is the x and y position of the mouse click. But then you need to make an estimation on where the mouse would have clicked. And that won't be accurate once the input field is overflowing.

Aruthar
  • 13
  • 1
  • 3

2 Answers2

1

Here is an example:

const inp = document.querySelector('#t1');

inp.addEventListener('click', e => {
  console.log(e.target.selectionStart);
});
<input type="text" id="t1" value="abcd">

This example is based on this post

InspectorGadget
  • 879
  • 6
  • 20
0

You might be looking for inputElement.selectionStart and InputElement.selectionEnd

I did a quick JSFiddle, hope it's what's you're looking for:

const input = document.getElementById("one");
const text = document.getElementById("mousepos");
const selectHandler = (evt) => {
  const starts = evt.target.selectionStart;
  const ends = evt.target.selectionEnd;
  const textSelected = evt.target.value.slice(starts, ends);
  text.innerHTML = starts + " - " + ends + " <br/> Text: "+ textSelected; 
}
input.addEventListener('click', selectHandler);
input.addEventListener('mousedown', selectHandler);
input.addEventListener('mouseup', selectHandler);

https://jsfiddle.net/12ow9br7/2/

savageGoat
  • 1,389
  • 1
  • 3
  • 10