javascripthtmldecimalonkeydown

I need an onkeydown function that limits the number of decimal places of that a html form can accept


For example, the html form should stop accepting decimal places after 0.1 so it wouldn't be possible to type in 0.01 to the html form box, thank for any help provided


Solution

  • You can use a regex to match values where there is only 1 decimal place. If the test fails, use Event.preventDefault:

    input.addEventListener("keydown", function(e){
      if(!/^(\d+)?([.]?\d{0,1})?$/.test(this.value + e.key)){
        e.preventDefault()
      }
    })
    <input id="input">