jQuery:在击键时自动将文本字段中的数字格式化为小数点后两位

发布于 2024-12-24 02:31:48 字数 288 浏览 3 评论 0原文

如何让输入字段(文本)只接受数字并在用户输入每个数字时自动将其格式设置为小数点后两位?

例如,该字段的默认值为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

提前致谢!

How do I get an input field (text) to accept only numbers and to automatically format it to two decimal places, as the user is typing in each digit?

For example, the default value of the field is 0.00
User wants to enter 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

Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

对你而言 2024-12-31 02:31:48

以下正则表达式匹配 99.99、99999.99 等。

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

使用 jQuery 的 .live() 函数将 keyup 事件连接到文本框。

$('.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
});

当 keyup 发生时,根据该正则表达式检查文本框的值,并根据您的答案执行您想要的操作。

要使其从右到左工作,您可以重新格式化字符串...

// 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.

将该逻辑填充到您的实时挂钩中。

the following regex expression matches 99.99, 99999.99, etc.

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

use jQuery's .live() function to wire the keyup event to your text box.

$('.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
});

when keyup happens, check the value of the text box against that regex expression and do what you wish with your answer.

to make it work from right to left you could reformat the string...

// 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.

stuff that logic inside your live hook.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文