Restrict input field to two decimals with jQuery

前端 未结 8 862
天命终不由人
天命终不由人 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:04

    
    

    The following function will restrict decimals according to your need of decimal places and also restrict more than one dot

    function check_digit(e,obj,intsize,deczize) {
        var keycode;
    
        if (window.event) keycode = window.event.keyCode;
        else if (e) { keycode = e.which; }
        else { return true; }
    
        var fieldval= (obj.value),
            dots = fieldval.split(".").length;
    
        if(keycode == 46) {
            return dots <= 1;
        }
        if(keycode == 8 || keycode == 9 || keycode == 46 || keycode == 13 ) {
            // back space, tab, delete, enter 
            return true;
        }          
        if((keycode>=32 && keycode <=45) || keycode==47 || (keycode>=58 && keycode<=127)) {
             return false;
        }
        if(fieldval == "0" && keycode == 48 ) {
            return false;
        }
        if(fieldval.indexOf(".") != -1) { 
            if(keycode == 46) {
                return false;
            }
            var splitfield = fieldval.split(".");
            if(splitfield[1].length >= deczize && keycode != 8 && keycode != 0 )
                return false;
            }else if(fieldval.length >= intsize && keycode != 46) {
                return false;
            }else {
                return true;
            }
        }
    }
    

提交回复
热议问题