如何防止十进制数字后按两位数?

Mon*_*ica 10 html javascript jquery textinput

我有一个任务,以防止在十进制数字后按两位数.我的jquery文件是

$(function(){ 
    $('#name').bind('paste', function(){
    var self = this;
    setTimeout(function() {
        if(!/^[a-zA-Z]+$/.test($(self).val()))
            $(self).val('');
    }, 0);    
           }); 

        $('#salary').bind('paste', function(){
    var self = this;
    setTimeout(function() {
        if(!/^\d*(\.\d{1,2})+$/.test($(self).val()))
            $(self).val('');
    }, 0);    
           }); 

    $('.decimal').keyup(function(){
        var val = $(this).val();
        if(isNaN(val)){
             val = val.replace(/[^0-9]./g,'');


             if(val.split('.').length>2) 
                 val =val.replace(/\.+$/,"");
        }
        $(this).val(val); 
    });
    });      
Run Code Online (Sandbox Code Playgroud)

我的html页面是

<b>Name</b>
<input type="text" id="name"  /><br/>
<b>Salary</b>
<input type="text" id="salary"  class="decimal" />
Run Code Online (Sandbox Code Playgroud)

在这里我只想在小数点后写2位数,我该怎么做?你可以在http://jsfiddle.net/V6s4B/看到我的代码

Dan*_*mms 13

您可以在keyup开启之前处理键事件keypress,如果输入不符合我们的喜好,我们可以禁用事件发生.像这样的东西:

更新

不幸的是,我的原始答案在某些无法准确表示为浮点数的数字上失败.这是另一种解决方案,它'.'使用方便的辅助函数检查字符的位置与字符串的长度.

的jsfiddle

$('.decimal').keypress(function (e) {
    var character = String.fromCharCode(e.keyCode)
    var newValue = this.value + character;
    if (isNaN(newValue) || hasDecimalPlace(newValue, 3)) {
        e.preventDefault();
        return false;
    }
});

function hasDecimalPlace(value, x) {
    var pointIndex = value.indexOf('.');
    return  pointIndex >= 0 && pointIndex < value.length - x;
}
Run Code Online (Sandbox Code Playgroud)

原始答案

的jsfiddle

$('.decimal').keypress(function (e) {
    var character = String.fromCharCode(e.keyCode)
    var newValue = this.value + character;
    if (isNaN(newValue) || parseFloat(newValue) * 100 % 1 > 0) {
        e.preventDefault();
        return false;
    }
});
Run Code Online (Sandbox Code Playgroud)

请注意,parseFloat(newValue) * 100 % 1 > 0如果newValue包含的小数位数超过2 ,则求值为true .