Search code examples
javascripttypescriptkeypressonkeypress

How to know the specific position in a String of a key pressed in the Keypress Event


I don't know if it is possible but i need to know the specific position where an character was entered using javascript. For example:

I have: 162345.25, if I want to entering another 6 number, between three and four numbers (1623645.25), I need to know in what position was entered (In this case, is the fifth position).

My problem is that I need to know that in the "keypress" event and I just can catch the key pressed. Somebody knows if it is possible?


Solution

  • let x = document.getElementById('x');
    x.addEventListener('keypress', () => console.log(x.selectionStart));
    <input id='x'>

    The keypress event won't know the cursor position. But if you have a specific element you're interested in, you can get element.selectionStart.