Restrict number of decimals in html5 type=“number” input field (with Angularjs model)

后端 未结 4 2171
太阳男子
太阳男子 2021-02-13 04:18

Please find the fiddle http://jsfiddle.net/q2SgJ/5/

WANTS: {{val | number:2}} in \"input\"
4条回答
  •  日久生厌
    2021-02-13 04:29

    I have extended the Tim's fiddle incase some one is looking for working solution

    http://jsfiddle.net/q2SgJ/653/

    modified the keypress event to retrieve the original typed value based on the cursor position

    ele.bind('keypress',function(e){
            var value = $(this).val();
                        var decimalPointPosition = value.indexOf(".");
                        if(!((e.charCode === 46) || (e.charCode > 47 && e.charCode <= 57)))
                            e.preventDefault();
    
                        else if (decimalPointPosition >= 0) {
                            var decimalCount = value.substring(decimalPointPosition + 1).length;
                            if ((decimalCount == 2 && $(this).prop("selectionStart") > decimalPointPosition)) {
                                e.preventDefault();                     
                }
               }       
    
            }
    

提交回复
热议问题