Restrict input field to two decimals with jQuery

前端 未结 8 786
天命终不由人
天命终不由人 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条回答
  •  不知归路
    2021-01-12 18:15

    A similar solution with a backspace hit on reaching more than 2 decimal places.

    function limitDec(id) {
      // find elements
      var amt = $("#testdec")
    
      // handle keyup
      amt.on("keyup", function() {
        if (isNaN(amt.val())) {
          amt.val(0);
        }
        if (amt.val().indexOf(".") > -1 && (amt.val().split('.')[1].length > 2)) {
          amt.val(amt.val().substring(0, amt.val().length - 1));
        }
      })
    }
    
    

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题