Input with Numbers Only

Only allows numbers in the input when the user types

by Rob Rothe

HTML

<div ng-app="mapApp">
    <label>LAT</label>
    <input type="text" ng-model="lat" numbersonly maxlength="50">
    <br>
    <label>LON</label>
    <input type="text" ng-model="lon" numbersonly maxlength="50">
</div>

JavaScript

var app = angular.module('mapApp', []);

app.directive('numbersonly', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            element.on('keydown', function (e) {
                var key = e.which;
                var charStr = String.fromCharCode(key);
                if (e.shiftKey === true) {
                    e.preventDefault();
                } else {
                    if (key != '32' && key != '9' && key != '8' && key != '110' && key != '190' && key != '13' && key != '46' && key != '189') {
                        // allow decimal, dashes numbers and shift key for capital letters only
                        if (!/[0-9]/.test(charStr) && (key < '95' || key > '105')) {
                            e.preventDefault();
                        }
                    }
                }
            });
        }
    }
});