javascript - 用于在文本输入中包含小数但不修改其小数的 Keyup 事件或输入掩码解决方案
问题描述
我一直在尝试很多解决方案来解决这个问题,但基本上我需要的是有一个输入,你可以在其中插入整数,但不能插入小数,而且总是将小数部分显示为“,00”。我一直在尝试使用 jquery-inputmask,但没有运气,也一直在玩事件,但只是有太多的情况需要用 event.which 来覆盖,这需要很长时间,最后可能是一个有风险的解决方案 2 或3 个错误,因为复制和粘贴数字,使用箭头键前进和后退。也不是用光标说,总是把它放在数字的末尾,不能改变小数点。
我的 jquery 解决方案是这样的:
$('input[type="text"]').keyup(function(event){
//In here I check for the user not to insert any period or comma's, as it will always be an integer at the end, also no spaces or letters
if (event.which == 32 || !(event.which >= 48 && event.which <= 57) && !(event.which >= 96 && event.which <= 105))
return false;
//In here I say if the text already have a comma, then check if the value is larger than zero, then add ",00" and set the cursor to the end of the integer part
if(!(this.value.indexOf(',') != -1)){
if(accounting.unformat(this.value, ',') >= 0){
this.value = this.value + ',00';
this.setSelectionRange(this.value.length - 3, this.value.length - 3);
}
}
});
正如您所看到的,它已经需要很多条件才能获得完全正确的用户体验,所以,我尝试并使用了 jquery-inputmask,并说如下:
$('input').inputmask('currency', {
prefix: '',
radixPoint: ',',
allowPlus: false,
allowMinus: false,
showMaskOnHover: false,
showMaskOnFocus: false,
clearMaskOnLostFocus: true,
rightAlign: false,
clearMaskOnLostFocus: true
});
这是一个非常好的解决方案,尽管它仍然让我更改小数。然后我又试了一个,就是把它当作小数而不是货币,然后去掉小数,给它加上一个后缀为'0,00',像这样:
$('input[type="text"]').inputmask('decimal', {
prefix: '',
suffix: ',00', // Adding digits here...
radixPoint: ',',
allowPlus: false,
allowMinus: false,
showMaskOnHover: false,
showMaskOnFocus: false,
clearMaskOnLostFocus: true,
rightAlign: false,
clearMaskOnLostFocus: true,
digits: 0 // removing digits here...
});
这有点工作,但是一旦我尝试输入一个欧洲数字,例如:1.234,00,它就不允许在文本框中输入这样的数字。更糟糕的是,如果我尝试输入逗号“,”,它就会开始变得疯狂并用逗号创建大量数字。
我正在使用这个插件: https ://github.com/RobinHerbots/Inputmask
以前有人遇到过这种情况吗?
谢谢!
解决方案
推荐阅读
- ios - 如何解码已经具有不同 API 解码逻辑的对象?
- python - 通过在 pandas 中添加匹配的单元格内容来创建新列
- php - 用数组传递值
- rust - 如何通过连接字符串文字来创建新标识符?
- python - 如何使用我所有选择的硬币在 python 上使用 Binance API 创建购买订单,而不是设置我要购买的硬币的数量?
- javascript - 通过使用 node-schedule (Node.js.) 在 javascript 中应用服务器时区来运行后台服务
- go - Go gorm 检查一个模型是否与另一个模型相关联
- node.js - 在 Node 测试中模拟和监视 API 依赖项的好方法是什么?
- python - Android上的低fps应用程序
- c# - 如何从剃须刀命令 Asp .net 核心中获取列的总和?