1

Based on this selectionStart/selectionEnd on input type="number" no longer allowed in Chrome and my own experiments, I understand that selectionStart and selectionEnd are null inside <input type="number"> elements. The question is, is there no way to get the caret position at all?

I tried using window.getSelection(), as suggested here: https://medium.com/javascript-in-plain-english/how-to-find-the-caret-inside-a-contenteditable-element-955a5ad9bf81 but this also seems to return 0, and not the actual caret position.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
AsGoodAsItGets
  • 2,886
  • 34
  • 49

1 Answers1

0

You can change the type attribute in target object:

const input = document.querySelector("input");
input.addEventListener("keyup", (e) => {
  const {target} = e;
  target.setAttribute("type", "text")
  console.log(target.selectionStart, target.selectionEnd)
})
<input type="number" />
lissettdm
  • 12,267
  • 1
  • 18
  • 39
  • Not sure what this does e.g. when the user has a mobile keyboard open. Does it switch from numeric to full when you switch the types? And anyway, it's a hack which I also read in the links above, I'd rather have a "clean" solution, thanks. – AsGoodAsItGets Feb 16 '21 at 16:59