質問

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

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

これは、私には乱雑に見えます。私は私が正しく機能をチェーンだとは思いません。私は、各テキストボックスのためにそれを呼び出す必要があり、または私は別の関数を作成することができますか?

役に立ちましたか?

解決

あなたはいくつかのフィールドにこれをやって、または非常に頻繁にそれをやっている場合は、おそらくプラグインが答えです。
ここでは小数点以下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));
});
あなたが入力を使用しているとき、それはもっと役立つことがあるため、

私たちは、keyUpイベントで使用する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
    });
});

DEMO ONLINEます:

http://jsfiddle.net/c4Wqn/する

(@ heridev、@vicmaster)

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top