0

I need to implement text-input in html, that: 1. user can press only digits 2. user can press max 4 digits.

Those are things that I know how to do, but I need that if user press less then 4 digits- so on lost focus - it will be completed to 4 digits by adding zero-digits at left-side as need.

How can I implement it?

Is there any way to implement all of the three requirements in on line? May be by jquery mask?

1 Answer 1

1
<input type="number" id="input_name">

This input only allows numbers in HTML5. To target this input do this:

var element = document.getElementByID('input_name');

Then add this code:

element.addEventListener('blur', function() {
   var elementLength = element.value.length;
   if(elementLength == 0) {
     return;
   }
   if(elementLength == 1) {
     element.value = '000'+element.value;
     return;
   }
   if(elementLength == 2) {
     element.value = '00'+element.value;
     return;
   }
   if(elementLength == 3) {
     element.value = '0'+element.value;
     return;
   }
   if(elementLength == 4) {
     return;
   }
   else {
     // Code to max the number of digits at 4
     element.value = element.value.substr(0, 3);
     return;
   }
}, false );

Hope this helps, Gab

Sign up to request clarification or add additional context in comments.

4 Comments

It is good, but isn't there any way to implement all of the three requirements in on line?
Sadly not one that I know, sorry hope this helps though
Also I don't know why someone down voted your question by I up voted it back to 0, because I think it is a good question.
Did it work? If so give the tick so the post is classified as answered.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.