用户输入时将输入值转换为货币格式 [英] Convert input value to currency format when user type

查看:66
本文介绍了用户输入时将输入值转换为货币格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我未能将输入值转换为货币格式.我想在用户输入数字 (5,000.00; 125,000.00) 时自动添加千位和小数点分隔符.

I have failed to convert the input value to currency format. I want to automaticly add thousands and decimal separators when the user types the number (5,000.00; 125,000.00).

这是我的代码:

$('input.CurrencyInput').on('blur, focus, keyup',
    function() {
        $(this).val().toLocaleString('en-US', {
            style: 'decimal',
            maximumFractionDigits: 2,
            minimumFractionDigits: 2
        });
    });

推荐答案

您的代码有几个问题:

  1. 在将多个事件处理程序绑定到输入框时使用逗号.
  2. 在对它应用 toLocaleString 之前,您没有将接收到的值转换为数字.
  3. 您没有在转换后再次设置文本框的值.
  1. You're using comma when binding multiple event handlers to the input box.
  2. You're not converting the received value to a number before applying toLocaleString on it.
  3. You're not setting the value of the textbox again after conversion.

纠正这些,这里是一个工作演示.为简单起见,我删除了除 blur 之外的其他事件处理程序,因为 keyup 会导致问题.

Correcting these, here is a working demo. For the sake of simplicity, I've removed the other event handlers, except blur, as keyup was causing problems.

$('input.CurrencyInput').on('blur', function() {
  const value = this.value.replace(/,/g, '');
  this.value = parseFloat(value).toLocaleString('en-US', {
    style: 'decimal',
    maximumFractionDigits: 2,
    minimumFractionDigits: 2
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="CurrencyInput">

这篇关于用户输入时将输入值转换为货币格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆