这就是我现在所拥有的:

$("#number").val(parseFloat($("#number").val()).toFixed(2));

它看起来杂乱无章我。我不认为我正确链接的功能。我必须调用它为每个文本框,或我可以创建一个单独的函数?

有帮助吗?

解决方案

如果你正在做这几个领域,或经常做,那么也许一个插件就是答案。结果 这里有一个jQuery插件,格式字段的到小数点后两位的价值的开端。结果 它是由现场的onchange事件触发。您可能需要不同的东西。

<script type="text/javascript">

    // mini jQuery plugin that formats to two decimal places
    (function($) {
        $.fn.currencyFormat = function() {
            this.each( function( i ) {
                $(this).change( function( e ){
                    if( isNaN( parseFloat( this.value ) ) ) return;
                    this.value = parseFloat(this.value).toFixed(2);
                });
            });
            return this; //for chaining
        }
    })( jQuery );

    // apply the currencyFormat behaviour to elements with 'currency' as their class
    $( function() {
        $('.currency').currencyFormat();
    });

</script>   
<input type="text" name="one" class="currency"><br>
<input type="text" name="two" class="currency">

其他提示

也许这样的事情,在这里你可以选择一个以上的元素,如果你想?

$("#number").each(function(){
  $(this).val(parseFloat($(this).val()).toFixed(2));
});

我们修改Meouw功能与KEYUP使用,因为当您使用的输入也可以是更有帮助。

检查这样的:

嘿!@heridev和我jQuery中创建了一个小的功能。

您可以尝试下一个:

HTML

<input type="text" name="one" class="two-digits"><br>
<input type="text" name="two" class="two-digits">​

的jQuery

// apply the two-digits behaviour to elements with 'two-digits' as their class
$( function() {
    $('.two-digits').keyup(function(){
        if($(this).val().indexOf('.')!=-1){         
            if($(this).val().split(".")[1].length > 2){                
                if( isNaN( parseFloat( this.value ) ) ) return;
                this.value = parseFloat(this.value).toFixed(2);
            }  
         }            
         return this; //for chaining
    });
});

在线演示:

http://jsfiddle.net/c4Wqn/

(@ heridev,@vicmaster)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top