0

我有一个条件允许用户只输入 2 个小数点数字并限制字母和其他字符。我使用了以下功能:

function isNumberKeyOnlyWithDecimalFormat(event,value,id){
        var val = value;
         if (event.shiftKey === true) {
                event.preventDefault();
        }
        if ((event.keyCode >= 48 && event.keyCode <= 57) ||
           (event.keyCode >= 96 && event.keyCode <= 105) ||
            event.keyCode == 8 || 
            event.keyCode == 9 ||  
            event.keyCode == 37 || 
            event.keyCode == 39 || 
            event.keyCode == 46 || 
            event.keyCode == 190) {

        } else {
            event.preventDefault();
        }
        if(val.indexOf('.') !== -1 && event.keyCode == 190){
            event.preventDefault();
        }
        if ((pointPos =   $('#'+id).val().indexOf('.')) >= 0){
            $('#'+id).attr("maxLength", pointPos+3);
        }
        else
            $('#'+id).removeAttr("maxLength");  
        }

第一次添加时工作正常。但它限制了如果我想编辑数字,如果它已经有 2 个小数位。有人能帮忙吗?

4

5 回答 5

3

尝试这个。每次焦点从输入字段消失时,它都会检查该值,但您可以使用任何您喜欢的事件。它会将值解析为浮点数,然后将其四舍五入到小数点后 2 位。

这是小提琴:http: //jsfiddle.net/sAp9D/

HTML:

<input type="text" id="the_id" />

JavaScript:

var input_field = document.getElementById('the_id');

input_field.addEventListener('change', function() {
    var v = parseFloat(this.value);
    if (isNaN(v)) {
        this.value = '';
    } else {
        this.value = v.toFixed(2);
    }
});
于 2013-07-29T05:48:03.877 回答
0

Your question is very hard to understand but if you want to check that a string has only 2 decimals then you can just do this

if( value.match(/\./g).length === 2 ) {
    // Number has 2 decimals eg. 1.2.3
} else {
   // Number is incorrect eg. 1.2.3.4
}

or if you want 1.2 then

if( value.match(/\./g).length === 1 ) {
    // Code....
}
于 2013-07-29T05:40:14.133 回答
0

我使用以下

// This function will only allow digits
function numericFormat( fld , e , extraStrCheck )
{
var sep = 0;
var key = '';
var i = j = 0;
var len = len2 = 0;
var strCheck = '0123456789';
if ( extraStrCheck )
    strCheck += extraStrCheck;
var aux = aux2 = '';
var whichCode = (window.Event) ? e.which : e.keyCode;

if (whichCode == 13) return true;  // Enter
if (whichCode == 8) return true;  // Backspace
if (whichCode == 0) return true;  // Null
if (whichCode == 9) return true;  // Tab

key = String.fromCharCode(whichCode);  // Get key value from key code
if ( strCheck.indexOf(key) == -1 ) return false;  // Not a valid key
var x = new String(fld.value);
if ( key == '.' )
{
    var exp = /\./;
    var a = x.search(exp);
    if ( a != -1 ) return false;
}


}

// samer code on change  or on blur event
function allow2decimal(obj){
    var v = parseFloat($(obj).val());



        if (isNaN(v)) {
            $(obj).value = '';
        } else {
            newVal = v.toFixed(2);
            if(newVal >= 100){
                $(obj).val( 100 );
            }else{
                $(obj).val(newVal);
            }

        }

}
//usage
  <input
        onkeypress="return numericFormat( this , event , '.');"
        onchange="allow2decimal(this)"
        value="0.1"
        id="factory_silk" name="factory_silk" />
于 2013-10-01T14:14:55.127 回答
0
<html>
    <head>
        <script type="text/javascript">  
        function NumAndTwoDecimals(e, field) {  
        var val = field.value;  
        var re = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)$/g;  
        var re1 = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)/g;  
        if (re.test(val)) {  

        }  
        else {  
        val = re1.exec(val);  
        if (val) {  
        field.value = val[0];  
        }  
        else {  
        field.value = "";  
        }  
        }  
        }  
        </script>  
    </head>
    <body>
        <input type="text" name="text" onkeyup="NumAndTwoDecimals(event , this);">  
    </body>
</html>
于 2016-12-16T09:47:01.483 回答
-1
$('.number').keypress(function(evt){
    var str = $(this).val();
    var index = str.indexOf('.');
    if(index==-1){index=0;}else{index= index+1;}
    var extrapoint = str.indexOf('.',index);
    if(extrapoint>0){$(this).val(str.slice(0,-1));}
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if(charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
    var validNumber = new RegExp(/^\d*\.?\d*$/);
    var lastValid = $(this).val();
    if (validNumber.test($(this).val()))
    {
        lastValid = $(this).val();
    } 
    else
    {
        $(this).val(lastValid);
    }
});
于 2018-03-07T11:36:33.870 回答