1

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?

Luis
  • 2,006
  • 5
  • 31
  • 47
  • In that case, someone is using the keyup event.. In my case, I need to do that using keypress event. – Luis Apr 12 '19 at 21:04

2 Answers2

6

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.

junvar
  • 11,151
  • 2
  • 30
  • 46
  • This doesn't seem to work with `` – Jibin Joseph Apr 12 '19 at 21:01
  • @JibinJoseph, you're right, apparently, this is an intended limitation for number inputs. See https://stackoverflow.com/questions/21177489/selectionstart-selectionend-on-input-type-number-no-longer-allowed-in-chrome/24175357 – junvar Apr 12 '19 at 21:12
0

Can you store the input's previous value (one value will be enough)? If so, then you can simply calculate the position of first difference between the new value and the old one.

mbojko
  • 13,503
  • 1
  • 16
  • 26