[英]How can I insert a zero in front of a number less than 10? HTML Input Box
I created an html input box where I would like a person to be able to enter at most 2 characters numbers (therefore from 01 to 99) and if the number is less than 10 the box must add zero by itself.我创建了一个 html 输入框,我希望一个人最多可以输入 2 个字符的数字(因此从 01 到 99),如果数字小于 10,则该框必须自行添加零。
There are 2 problems:有2个问题:
00
, the script writes 000
;如果我输入00
,脚本会写000
; if I write 01
the script writes 001
, etc.如果我写01
脚本写001
等。Code:代码:
<input type="number" class="form-control" name="amount_centesimi" min="0" max="99" value="00" onchange="if(parseInt(this.value,10)<10)this.value='0'+this.value;" required>
try this.尝试这个。
<input type="number" class="form-control" name="amount_centesimi" min="0" max="99" value="00" onchange="this.value=(parseInt(this.value)<10)?('0'+parseInt(this.value)):parseInt(this.value)" style="width: 100px" required>
There was two problem in your code:您的代码中有两个问题:
if (parseInt(this.value,10) < 10) this.value= '0' + this.value;
this.value
. 1 将值分配给this.value
时,您错过了对其进行清理。 You write code that this.value = '0' + this.value;
你写的代码this.value = '0' + this.value;
So, if your input value was '01'
, js use the raw string value and make it '001'
( '0' + '01'
)因此,如果您的输入值为'01'
,则 js 使用原始字符串值并将其'001'
( '0' + '01'
)
You had to sanitize the value like this:您必须像这样清理值:
this.value = '0' + parseInt(this.value)
Or, if you input value like '000999', it will not changes to '999'或者,如果您输入类似 '000999' 的值,它不会更改为 '999'
Not sure if I'm doing it right, but when I used onChange
it didn't update the value instantly, so I've used onInput
.不确定我是否做得对,但是当我使用onChange
它没有立即更新值,所以我使用了onInput
。
Since I couldn't think of a way to track the previous value it will roll over if you keep typing numbers.由于我想不出一种方法来跟踪以前的值,如果您继续输入数字,它会翻转。
<input min="0" max="99" value="00" type="number" oninput="(function(e) { let value = e.value.replace(/\\D/g,''); if (parseInt(value, 10) < 10) { value = '0' + value; } e.value = value.substr(-2); })(this);" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.