[英]Ember input type number to allow only 2 digits after Decimal
I am working on an Ember application, an input type number as below我正在开发一个 Ember 应用程序,输入类型编号如下
${{input type="number" id=p.ViolationTypeId
value=p.PenaltyAssessed maxlength="5"
scale="0.01" pattern="^\d+(\.\d{0,2})?$"
key-down=(action 'allowOnly2Decimals')
focusOut=(action 'saveTotalPenalty' p model.id p.PenaltyAssessed)}}
Then I have a following JavaScript Code written to limit the entry of digits after decimal, this function is called in Key-Down event.然后我写了一个以下 JavaScript 代码来限制十进制后数字的输入,这个 function 在 Key-Down 事件中被调用。
allowOnly2Decimals: function (e1, event) {
var boxId = '#' + event.path[0].id;
//if ((event.keyCode == 190) || (event.keyCode == 110)) {
// this.decimalPressed = true;
//}
var t = e1.toString().split('.');
if (t[1] != null) {
if (t[1].length == 2) {
this.limitDecimal = e1;
$(boxId).val(e1);
}
if (t[1].length >= 2) {
e1 = this.limitDecimal;
$(boxId).val(e1);
return false;
}
}
}
}
Its working but what it is doing it, it allowing 3 digits after decimal but when I am posting its value on the Service, that is taking correctly 2 digits after decimal but what it is showing in the Textbox is 3 digits after decimal.它可以工作,但它正在做什么,它允许小数点后 3 位数字,但是当我在服务上发布它的值时,它正确地采用了小数点后 2 位数字,但它在文本框中显示的是小数点后 3 位数字。 And another request if possible is, can I do the same without using id attribute on the Textbox.
如果可能的话,另一个请求是,我可以在不使用文本框上的 id 属性的情况下做同样的事情吗?
Any help please, thanks in advance.请任何帮助,在此先感谢。
To answer your first question, the reason it is allowing 3 values is because you are using the keydown
event.要回答您的第一个问题,它允许 3 个值的原因是因为您正在使用
keydown
事件。 The keydown
event is fired before the input is updated so you're always 1 character behind the actual value.在更新输入之前触发
keydown
事件,因此您始终落后于实际值 1 个字符。 I would recommend instead of using keydown, to use the change event .我建议不要使用 keydown 来使用change event 。 If you really have to mangle the user's inputs as they type, use the keyup event instead.
如果您确实必须在用户键入时破坏用户的输入,请改用 keyup 事件。
To answer your second question, you can access the input via event.target
ie $(event.target).val(e1);
要回答您的第二个问题,您可以通过
event.target
访问输入,即$(event.target).val(e1);
Finally your code is making some assumptions about the user's input, what happens if they paste in a value that is longer than 2 characters after the decimal?最后,您的代码对用户的输入做出了一些假设,如果他们粘贴的值超过小数点后 2 个字符,会发生什么情况?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.