Reputation: 45
I want to disable the up and down keys for a number input through angularjs directive (or otherwise).
Note: I don't want to change the input type to text as I have been asked not to.
I already removed the spinners too.
I am new to angular so don't know much about it. I googled through all the links I could find but they were mostly about hiding the spinners and not about disabling the arrow keys.
I got this code from some other link. This disables the mousewheel for the same. If some changes to this can be done, that will 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');
});
}
}
}
});
Upvotes: 3
Views: 6314
Reputation: 32357
If you want to disable up/down arrow keys globally for all input[number] 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 a single element with a 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 />
Upvotes: 5
Reputation: 6075
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');
});
}
}
}
});
Upvotes: 1