26
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

jQueryで3桁カンマ区切り

Last updated at Posted at 2015-12-15

覚書。

やりたいこと

  • テキストボックスからフォーカスが外れたタイミングでカンマ区切り。
  • テキストボックスにフォーカスをあてたタイミングでカンマを除去。

やり方

カンマ区切りさせたいテキストボックス。

HTML
<input type="text" id="textBox" value="123456789" />

フォーカスが外れたときは、正規表現を使ってカンマ区切り。
フォーカス時はカンマを除去。

jQuery
$(function() {
  
  // フォーカスアウト
  $('#textBox').on('blur', function(){
    var num = $(this).val();
    num = num.replace(/(\d)(?=(\d\d\d)+$)/g, '$1,');
    $(this).val(num);
  });
  
  // フォーカス
  $('#textBox').on('focus', function(){
    var num = $(this).val();
    num = num.replace(/,/g, '');
    $(this).val(num);
  });
  
});

(2015/12/21追記)
上記のソースだと整数しか対応できていないので、
少数入力したときに小数点以下しかカンマ区切りされない・・・

正規表現のところを書き換えます。


num = num.replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');

デモ

参考

http://qiita.com/ariyo13/items/ab410a84c74b23099648
http://qiita.com/think49/items/b1bf02e5f4cfbb200b84

26
21
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?