Reputation: 1337
I want to my textbox to only allow numbers and also have a character limit on it.
Currently, I have the numbers working... Now I am having issues figuring out how to limit the characters.
Here is what I have...
JS:
app.directive('numbersonly', function () {
return {
restrict: 'A',
link: function (scope, elm, attrs, ctrl) {
elm.on('keydown', function (event) {
if (event.which == 64 || event.which == 16 && elm.val().length > 4) {
return false;
} else if (event.which >= 48 && event.which <= 57) {
return true;
} else if (event.which >= 96 && event.which <= 105) {
return true;
} else if ([8, 13, 27, 37, 38, 39, 40].indexOf(event.which) > -1 && elm.val().length > 4) {
return true;
} else {
event.preventDefault();
return false;
}
});
}
}
});
Markup:
<input type="text" id="txtEmpAge" data-ng-model="newemployee.Age" class="form-control" numbersonly required />
Upvotes: 4
Views: 19159
Reputation: 13817
I had the same issue and wrote a directive to figure it all out. Then I found a plug in called angular-dynamic-number and it worked for me right out the box. I would suggest you use that if it meets your need. https://www.npmjs.com/package/angular-dynamic-number
Upvotes: 0
Reputation: 1073
In html input attribute length. we can use it in multiple forms:
Length, Minlength and maxlength
Try this
maxlength="5"
Upvotes: 9