2

Hi community!

What would be the proper way to add a unit inside a number input?

The goal is not to add a span with a negative left margin to come over the input, but to really insert a non-editable unit directly after the number, adapting to the number length:

[....3€....]
[...333€...]
[..33333€..]

I've found this calculator to achieve this result quite elegantly, but can't figure how to get the same effect.

Any ideas?

Louis
  • 21
  • 3
  • The linked site doesn't use a number input, it has a custom component built with contenteditable divs – pilchard Apr 14 '22 at 20:39
  • Does this answer your question? [html5 input for money/currency](https://stackoverflow.com/questions/24163889/html5-input-for-money-currency) – pilchard Apr 14 '22 at 20:42
  • Could you explain a bit more what “really insert” means as it would clash with “non editable”. Is it that you want any code asking for the .value to include the euro sign? – A Haworth Apr 14 '22 at 21:16

1 Answers1

0

First of all Don't use input of a type number for this one because it will not allow you to use currency symbol.

Now, create an input and listen for keypress. If it's a number or minus sign or a dot intert it before the symbol.

input.addEventListener('keypressed', event => {
  const codes = [] // check the codes here https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values
  if (codes.includes(event.key)) return
  input.value = input.value.slice(0, -1) + event.key // probably some mapping needed
})

The code above is an untested proof of concept

Konrad
  • 21,590
  • 4
  • 28
  • 64
  • 1
    How does this deal with the user editing from the middle of the number, for example using arrow keys to move the cursor or touching part way down the string? Additions are not always at the end of the value. – A Haworth Apr 14 '22 at 21:31