0

我试图在输入数字时自动更改为十进制的输入,但仅固定为 2 个十进制点。请帮助我,因为我还是 jquery 的新手

我的代码:

 $.fn.billFormat = function() {
        $(this).keyup( function( e ){
                if( isNaN(parseFloat(this.value )) ) return;
                this.value = parseFloat(this.value).toFixed(2);
        });
        return this; 
 }

$('#ENQUIRY_PREPAIDBILL .bill_issued').billFormat();

我希望输出是这样的

0.00 <------ 默认值
0.01 <----- 输入 1
0.10 <----- 输入 0
1.00 <----- 输入 0

4

2 回答 2

2
 $.fn.billFormat = function() {
        this.val("0.00");
        this.keyup( function( e ){
                if( isNaN(parseFloat(this.value )) ) return;
                this.value = parseFloat(this.value * 10, 10).toFixed(2);
        });
        return this; 
 }

这是演示

于 2012-06-15T02:52:44.850 回答
0

这是另一种无需担心溢出的解决方案(您可以在此处找到演示

$(document).ready(function(){
    $('#txtInput').keydown(function(e){
        var value = $('#txtInput').val().toString();
        var number = null;
        if(value == '')
            value = '0.00';
        switch(e.which)
        {
            case 48:
            case 49:
            case 50:
            case 51:
            case 52:
            case 53:
            case 54:
            case 55:
            case 56:
            case 57:
                number = e.which - 48;
            case 8:
            case 46:
            case 32:
            case 37:
            case 38:
            case 39:
            case 40:
                break;
            default:
                e.preventDefault();
                break;
        }
        var dotIndex = value.indexOf('.');
        if(number === null)
        {
            value = value.substr(0,dotIndex-1) + '.' + value.substr(dotIndex -1,1) + value.substr(dotIndex+1,1);
            if(value.indexOf('.') ==0)
            {
                value = '0' + value;
            }
        }
        else
        {

            value = value.substr(0,dotIndex) + value.substr(dotIndex+1,1) + '.' + value.substr(dotIndex+2);

            value += number.toString();  
            value = value.replace(/^0+/,'');
            if(value.indexOf('.') == 0)
            {
                value = '0' + value;
            }               

        }
        $('#txtInput').val(value);
        e.preventDefault();
    }).keyup(function(e){

        switch(e.which)
        {
            case 48:
            case 49:
            case 50:
            case 51:
            case 52:
            case 53:
            case 54:
            case 55:
            case 56:
            case 57:
                e.preventDefault();
                break;
        }
    });
});​

和这段代码的 html

<input type='text' id='txtInput' />​
于 2012-06-15T04:19:00.987 回答