70

これは私が今持っているものです:

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

私には乱雑に見えます。関数を正しく連鎖しているとは思いません。テキストボックスごとに呼び出す必要がありますか、それとも別の関数を作成できますか?

4

3 に答える 3

108

これを複数のフィールドで実行している場合、または頻繁に実行している場合は、おそらくプラグインが答えです。
これが、フィールドの値を小数点以下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">
于 2009-01-25T20:55:25.780 に答える
65

必要に応じて複数の要素を選択できる、このようなものでしょうか?

$("#number").each(function(){
    $(this).val(parseFloat($(this).val()).toFixed(2));
});
于 2009-01-25T16:59:47.940 に答える
4

入力を使用しているときに、より役立つ可能性があるため、キーアップで使用する Meouw 関数を変更します。

これをチェックして:

@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)

于 2012-11-27T16:33:08.253 に答える