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.
There are 2 problems:
00
, the script writes 000
; if I write 01
the script writes 001
, etc.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
. You write code that this.value = '0' + this.value;
So, if your input value was '01'
, js use the raw string value and make it '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'
I would use padStart :
<input
type="number"
class="form-control"
name="amount_centesimi"
min="0"
max="99"
value="00"
onchange="this.value = this.value.padStart(2, '0')"
required />
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
.
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);" />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.