Reputation: 41
Here I have a text box. In that field There is a validation that need to allow only numeric,alphabets and spanish characters. For that I found a function in javascript. That function is in ng-keypress, I want to change it to ng-change. If I change, The function is not firing.
How to change the function to ng-change.
JSP code:-
<input type="text" ng-model="name" ng-keypress="getPatternForAlphebet($event,$index)">
script code:-
$scope.getPatternForAlphebet = function(event,rowIndex){
var key = key || event.which;
if($scope.documentTypeNumber==1 || $scope.documentTypeNumber ==2){
if ((key > 64 && key < 91)|| (key > 159 && key < 166) || (key > 96 && key < 123) || (key == 165) ||(key == 32)
|| (key == 164) || (key == 130) || (key == 181) || (key == 144) || (key == 214) ||
(key == 224) ||(key == 233) || (key == 8) || (key == 241) || (key == 209)) {
}else{
event.preventDefault();
}
}else if($scope.documentTypeNumber==6){
if ((key > 64 && key < 91)|| (key > 159 && key < 166) || (key > 96 && key < 123) || (key == 165) ||(key == 32) ||
(key == 59) || (key == 164) || (key == 58) || (key == 46) || (key == 44) || (key == 38) ||
(key == 34) || (key == 130) || (key == 181) || (key == 144) || (key == 214) ||
(key == 224) ||(key == 233) || (key == 8) || (key == 241) || (key == 209)) {
}else{
event.preventDefault();
}
}
};
Upvotes: 2
Views: 1652
Reputation: 842
I think you can use a directive instead. Please find the following code update it as you need, I hope this will help. Please add the key codes for Backspace and delete in both. Thank you
<input type="text" ng-model="name" documentvalue="{{documentTypeNumbe}}" filtered-character>
directive('filteredCharacter', function () {
return function (scope, element, attrs) {
element.bind("keydown paste", function (event) {
//console.log($.inArray(event.which,keyCode));
var keyCode = [];
if (attrs.documentvalue == 1 || attrs.documentvalue == 2) {
keyCode = [65, 91, 159]; // Please add all the required key codes
} else if (attrs.documentvalue == 6) {
keyCode = [67, 93, 161]; // Please add all the required key codes
}
if ($.inArray(event.which, keyCode) === -1) {
scope.$apply(function () {
scope.$eval(attrs.filteredCharacter);
event.preventDefault();
});
event.preventDefault();
}
});
};
});
Upvotes: 0
Reputation: 2658
ng-change
must be used with ng-model
. So, add ng-model
to the input field.
Read more about ng-change
here
EDIT :
As Alexis Toby said, ng-change
does not have $event
. Remove it. It will work.
Upvotes: 1
Reputation: 71
Try calling the same the function using "ng-keydown". Follow the link to this plunker
<input type="text" ng-model="name" ng-keydown="getPatternForAlphebet($event,$index)">
Upvotes: 0