UPDATE
I fixed the error code and added var named key to save the pressed code using keyCode and which are browser dependent.
var key = e.which || e.keyCode;
Thanks Donald.McLean :)
If you want to check whether you write down numbers during input (and do not write other characters in the input field), you can use this simple function and you can define the allowed elements (including everything that you want to filter). Thus, you can choose not only integers, but, for example, a certain group of characters. The example is based on jQuery to attach it to an input field.
$('#myInputField').keypress(function(e) { var key = e.which || e.keyCode; if (!(key >= 48 && key <= 57) && // Interval of values (0-9) (key !== 8) && // Backspace (key !== 9) && // Horizontal tab (key !== 37) && // Percentage (key !== 39) && // Single quotes (') (key !== 46)) // Dot { e.preventDefault(); return false; } });
If you use a key other than a specific one, it will not appear in the field. And since Angular.js is getting strong these days. this is a directive that you can create for this in any field of your web application:
myApp.directive('integer', function() { return function (scope, element, attrs) { element.bind('keydown', function(e) { var key = e.which || e.keyCode; if (!(key >= 48 && key <= 57) &&
But what happens if you want to use ng-repeat , and you need to apply this directive only in a certain number of fields. Well, you can convert the top directive into one prepared in order to recognize the value true or false in order to be able to decide which field will depend on it.
myApp.directive('rsInteger', function() { return { restrict: 'A', link: function (scope, element, attrs) { if (attrs.rsInteger === 'true') { element.bind('keydown', function(e) { var key = e.which || e.keyCode; if (!(key >= 48 && key <= 57) &&
To use this new directive, you just need to do this in input type text, for example:
<input type="text" rs-integer="true">
Hope this helps you.