简体   繁体   中英

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.

There are 2 problems:

  1. If I type 00 , the script writes 000 ; if I write 01 the script writes 001 , etc.
  2. The box accepts numbers over 99

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;

1 You missed to sanitize the value when you assign it to 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)

2 You had to change the value even if the input number was greater than 10

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.

  • Type 0 - get 00
  • Type 1 - get 01
  • Type 1 - get 11
  • Type 2 - get 12
  • Type 3 - get 23

 <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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM