Disable arrow keys to enter numbers using angles
I want to disable the up and down keys for number input via angularjs directive (or otherwise).
Note. I don't want to change the input type to text as I was asked not to do. I already removed the spinners too. I'm new to angular so don't know much about this. I searched for all the links I could find, but they were mostly about hiding spinners, not disabling the arrow keys. I got this code from another link. This disables the mouse wheel. If some changes to this can be done, that would be great.
module.directive('input',function() {
return {
restrict: 'E',
scope: {
type: '@'
},
link : function (scope, $element) {
if (scope.type == 'number') {
$element.on('focus', function () {
angular.element(this).on('keyup', function (e) {
e.preventDefault();
});
});
$element.on('blur', function () {
angular.element(this).off('keyup');
});
}
}
}
});
+3
source to share
2 answers
If you want to disable the up / down arrow keys globally for all [number] input elements:
$(document).bind('keydown', function(event) {
var target = event.srcElement || event.target;
var tag = target.tagName.toUpperCase();
var type = target.type.toUpperCase();
if (tag === 'INPUT' && type === 'NUMBER' &&
(event.keyCode === 38 || event.keyCode === 40)) {
event.preventDefault();
}
});
Or you can bind it to one element with the directive:
.directive('disableArrows', function() {
function disableArrows(event) {
if (event.keyCode === 38 || event.keyCode === 40) {
event.preventDefault();
}
}
return {
link: function(scope, element, attrs) {
element.on('keydown', disableArrows);
}
};
});
template:
<input type="number" disable-arrows />
+5
source to share
You can change your directive to:
module.directive('input',function() {
return {
restrict: 'E',
scope: {
type: '@'
},
link : function (scope, $element) {
if (scope.type == 'number') {
$element.on('focus', function () {
angular.element(this).on('keyup', function (e) {
if (event.keyCode === 38 || event.keyCode === 40) {
e.preventDefault();
}
});
});
$element.on('blur', function () {
angular.element(this).off('keyup');
});
}
}
}
});
+1
source to share