【问题标题】:User input currency extra decimal [duplicate]用户输入货币额外小数 [重复]
【发布时间】:2021-05-18 13:35:19
【问题描述】:

我有一个用户输入框,用户可以在其中输入美元货币的数量。当用户输入小数来表示美分时。 0.24 当输入为 0.244 或 .240 时,该值显示为 0.20 而不是 0.24,它显示为 0.24 美分。我希望用户能够只输入 0.24 美分,而不必输入额外的小数。

var $partialText = $('#partialText');

$partialText.on('keypress', function() {
var $dark = parseFloat($partialText.val()); //Take the input value of partial input as a number

console.log($dark);

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" name="partial" id="partialText" size="15" maxlength="6" />

【问题讨论】:

  • 请编辑您的问题并包含相关的 HTML 和任何 CSS。
  • 请在您的 sn-p 中提供足够的代码,以便有人可以单击 Run code sn-p 并查看您要询问的内容。请参阅How to Askminimal reproducible example 了解更多信息。

标签: javascript


【解决方案1】:

您可以改用input 事件,它还将处理诸如将文本粘贴到字段中的情况。

var $partialText = $('#partialText');

$partialText.on('input', function() {
var $dark = parseFloat($partialText.val()); //Take the input value of partial input as a number

console.log($dark);

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" name="partial" id="partialText" size="15" maxlength="6" />

【讨论】:

  • 这个例子有效。
【解决方案2】:

您在onKeyPress 处理程序中收到的值落后于您输入的值。这应该会有所帮助:How to get text of an input text box during onKeyPress?

【讨论】:

    猜你喜欢
    • 2015-03-15
    • 2014-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-21
    • 2013-03-27
    • 1970-01-01
    相关资源
    最近更新 更多