AsGoodAsItGets
AsGoodAsItGets

Reputation: 3181

How to get the caret position inside input type="number" element?

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.

Upvotes: 2

Views: 492

Answers (1)

lissettdm
lissettdm

Reputation: 13078

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" />

Upvotes: 0

Related Questions