使用jquery如何在数字形式输入中自动填充逗号?

时间:2009-09-21 17:57:30

标签: jquery

我是jquery的新手,似乎无法弄清楚如何做到这一点。基本上,当在表单文本字段中键入一个大数字时,我希望逗号自动放在用户的字段中,而不必自己键入它们。谁能帮我解决这个问题呢?

感谢。

4 个答案:

答案 0 :(得分:3)

我认为您想要一种屏蔽输入,请检查this插件。

答案 1 :(得分:2)

您可以使用数字formatter plugin

以下是插件页面的一些示例(上面给出的链接):

  // Brazilian currency format
  $(".numeric").number_format({precision: 2, decimal: ',', thousands: '.'});

  /* Results: number are formatted as they are typed
  123,45
  1.234,56*/
  // Changing precision to 5 decimal digits
  $(".numeric").number_format({precision: 5});

  /* Results: number are formatted as they are typed
  1,234.56789 
  0.12345 */

答案 2 :(得分:0)

关闭我的头顶无法输入字段上有格式掩码。如果没有,有人拿枪对我说现在这样做,我会拿着可携带的长度拿着数字数据然后除以3,我知道我需要多少逗号。然后使用javascript使用substring方法从右边抓取每个三个并在它之前放置一个逗号。

答案 3 :(得分:0)

当用户离开文本框时,使用blur事件重新格式化数字。

$(".selector").blur(function() {
  $(this).val() = commafyValue($(this).val());
}

我从here中删除了一个commafy函数,但是有很多可供选择,或者你可以编写自己的...

function commafyValue(nStr)
{
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}