Restrict input field to two decimals with jQuery

前端 未结 8 843
天命终不由人
天命终不由人 2021-01-12 17:46

I have an input field which I want to restrict so that the user only can input a number with the maximum of two decimals. Want to do this using jQuery.

Could I use j

8条回答
  •  梦毁少年i
    2021-01-12 18:03

    A HTML5 solution:

    
    

    Demo

    If you want to style invalid inputs (some browsers do it by default), you can use :invalid selector:

    input:invalid {   box-shadow: 0 0 1.5px 1px red;   }
    

    Note this approach won't attempt to truncate the number automagically, but if the user enters more than two decimal digits, the input will become invalid, and thus the form won't be submitted:

    Screenshot on Firefox

提交回复
热议问题