input[type=number]
by definition only accepts integers as input. Try it out yourself. Try typing in letters and it won't allow you.
There's no need for JavaScript as it's already built in. Did you perhaps mean input[type=text]
?
You can accomplish that via angular directives. It would look something like this (not sure about my syntax though)
app.directive('onlyNumbers', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind("keydown", function(event) {
if ((event.keyCode > 47 && event.keyCode < 58) && !event.shiftKey) {
event.preventDefault();
return false;
}
});
}
});
The syntax might have a few errors, but I will break down the basic formula.
Since we are working with an input element, it makes sense that we use an attribute
directive. We can do this, by setting the restrict
property to A.
Since we will be listening for keypress events, we should use the link
function. We want to listen for the keydown
event, to detect when a key is starting to be pressed.
To find if the user typed a number, we will use keyCodes
, for which the number keys are 48 through 57 representing 0 through 9 respectively. However, we didn't account for special characters, which require hitting the number keys. So we make sure the shift key isn't being pressed either.
Then we can add this directive as an attribute on our input element.
<input type="text" only-numbers />