One liner to generate dynamically the step attribute for a number type input?

I have an input of type number :

<input type="number">

There is no step attribute, but the user can start to enter a number like “21”, “1.12”, “0.00123”, and on keydup, a script will determine the proper step. So for instance for 21 that would be 1, for 1.12 that would be 0.01, for 0.00123 that would be 0.00001, and so on.

I tried this:

input.addEventListener('keyup', (e) => {
  const value = input.value;
  if (value.split('.').length === 1) {
    input.step = 1
    return
  }
  
  let precision = value.split('.')[1].replace(/./g, '0')
  precision = `0.${precision.substring(0, precision.length - 1)}1`
  console.log(`precision: ${precision}`)

  input.step = precision
})
<input type="number" id="input">

It seems to work, but how can I apply this process (in the event handler function) in a one liner?

Answer

this should do the trick:

document.querySelector('input').addEventListener('keyup', (e) => {
  console.log(`precision: ${1 / Math.pow(10, input.value.split('.')[1]?.length ?? 0)}`)
})
<input type="number" id="input">

Leave a Reply

Your email address will not be published. Required fields are marked *