Skip to content Skip to sidebar Skip to footer

Leading Zeros Missing Within Number Input

I need to have displayed, within the number input field, the leading zeros on integers between 00-09. I am using angularJS. View/template for the input field(sorry for the style wi

Solution 1:

I'm not fond of this solution - there's an annoying flicker with this approach, and I'm especially not pleased with the setTimeout call - but it seems to work, and avoids the annoying "that's not a number" error Angular throws.

angular.module('application', [])
    .directive('zeroPadded', function(){
        return{
            // limit to classes and attributes only
            // to use with CSS class, include "zeroPadded" in the class attribute
            // to use with attributes, add "zero-padded" to the input tag
            restrict: 'AC',
            link : function(scope, element){
                function padZeroesElement(ele){
                    if(ele.value < 10){
                        ele.value = "0" + ele.value;
                    }
                };

                function padZeroes(event){
                    padZeroesElement(event.target);
                };

                element.on('change', padZeroes);

                // hacky but not sure how else to ensure it's zero-padded   from the start
                setTimeout(function(){
                    for(var i = 0; i < element.length; i++){
                        padZeroesElement(element[i]);
                    }
                }, 1000);
            }
        };
    });

And then your actual input looks something like this:

<input type="number" id="minute" ng-model="minute" min="0" max="59" step="1" zero-padded />

Solution 2:

I'm encountering a similar issue, where leading zero's are being trimmed from my "text" input. When I call ngModel.$setViewValue("123.8900") the text displayed in the input is "123.89" (the model is correctly set with zeros).

To solve this issue while still correctly setting the model, I call both:

var value = "123.8900";
ngModel.$setViewValue(value); //updates model but trims zeros in the view
inputEl[0].value = value; //prevents trimming of trailing zero but this alone wont update the model

Post a Comment for "Leading Zeros Missing Within Number Input"