[英]How to make an HTML number input that transforms its value to tenths (possibly using jQuery)
Let's say I have an input field like假设我有一个输入字段,例如
<input type='number' id='input-tenths' />
What I want to achieve in this, is the digits I put into this field being treated as "tenths" instead of whole numbers, for example:我想在此实现的是,我在此字段中输入的数字被视为“十分之一”而不是整数,例如:
3
in this input field, I want the value of the field to be 0.3
当我在此输入字段中输入3
时,我希望该字段的值为0.3
5
, I want the value to become 3.5
之后,当我输入5
,我希望该值变为3.5
9
, the value should become 35.9
...然后是9
,该值35.9
I have so far tried to add a hidden field <input type='hidden' id='hidden-tenths'/>
, and a function like到目前为止,我已经尝试添加一个隐藏字段<input type='hidden' id='hidden-tenths'/>
,以及一个像
$('#input-tenths').on('input', function(e){
$('#hidden-tenths').val($('#hidden-tenths').val() + '' + $(this).val().slice(-1));
$(this).val($('#hidden-tenths').val() / 10);
$('#hidden-tenths').val($(this).val() * 10);
});
but this doesn't always work as expected (for example, when I backspace in the original input, a digit is appended rather than removed, as can be expected from using the .slice(-1)
.但这并不总是按预期工作(例如,当我在原始输入中退格时,会附加而不是删除数字,正如使用.slice(-1)
所预期的.slice(-1)
。
What would be a good way to achieve the expected behaviour, where I'm trying to stay away from explicitly binding all key presses and thereby essentially reprogramming the input field (except when this is the only way to achieve this).什么是实现预期行为的好方法,我试图避免显式绑定所有按键,从而基本上重新编程输入字段(除非这是实现此目的的唯一方法)。
$('#input-tenths').on('input', function(e) { $('#hidden-tenths').val($('#hidden-tenths').val() + '' + $(this).val().slice(-1)); $(this).val($('#hidden-tenths').val() / 10); $('#hidden-tenths').val($(this).val() * 10); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type='number' id='input-tenths' /> <input type='number' id='hidden-tenths' />
Change opacity from .3 to 0 when happy.开心时将不透明度从 0.3 更改为 0。 You may want to suppress decimals你可能想抑制小数
$('#hidden-tenths').on('input', function(e) { $('#input-tenths').val((this.value/10).toFixed(1)) });
#input-tenths { opacity:1; position:absolute; z-index:0; } #hidden-tenths { opacity:.3; position:absolute; z-index:100; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type='number' id='input-tenths' /> <input type='number' id='hidden-tenths' />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.