2011-12-30 3 views
2

入力フィールド(テキスト)を入力するだけで、数字だけを受け取り、自動的に小数点以下2桁までフォーマットします各桁?例えばjQuery:キーストロークの2桁の小数点までのテキストフィールドの数値の自動書式設定

は、フィールドのデフォルト値は0.00 ユーザーが事前に23.50

Step 1: user types 2 - field shows 0.02 
Step 2: user types 3 - field shows 0.23 
Step 3: user types 5 - field shows 2.35 
Step 4: user types 0 - field shows 23.50 

感謝を入力したいです!

答えて

0

次の正規表現式は99.99と一致し、99999.99など

\$\d+\.\d{2} 

テキストボックスにからkeyupイベントを配線するjQueryの.live()関数を使用します。

$('.textBoxDecimalOnly').live('keyup', function() { 
    // inside this keyup hook, grab the value in the text box. 
    // if it matches the regex... do something 
    // else do something different 
}); 

キーアップが発生した場合、テキストボックスの値をその正規表現と照合して、あなたの答えにしてください。

それはあなたが文字列を再フォーマット可能性が右から左に動作させるために...

// 1. get text in the box. 
// 2. if length < 3 ... append a "." to the first string. 
// 3. if > 3 get the index of the 2nd to last character and append "." just before it. 

ものそのライブフック内部のロジック。

+0

お返事ありがとうございます! – Spartanblogger

関連する問題