0

Directive defined to add numeric input

    app.directive('numericCheck', function () {
    return {
        link: function (scope, element, attr) {
            element.on('keypress', function (event) {  
                event = (event) ? event : window.event;
                if(/Firefox/.test(window.navigator.userAgent) && event.keyCode!=0) {
                    return true;
                }
                var charCode = (event.which) ? event.which : event.keyCode;
                if (charCode > 31 && charCode != 46 && charCode != 47 && charCode != 45 && (charCode < 48 || charCode > 57) || (charCode==45 && (event.target.selectionStart!=0 || event.target.value.indexOf('-')>=0)) || (charCode==46 && event.target.value.indexOf('.')>=0) || (charCode==47 && (event.target.selectionStart==0 || event.target.value.indexOf('/')>=0))) {
                    return false;
                }
                return true;
            });  
        }

    };
});

The below string is the response added to a div.

{"question":"Two identical charts have different parts shaded. Which one is greater - 0.02 or 0.04?<br><br><br><br><input type='text' id='b1' name='blank_1' class='num_blank' size='5' numeric-check> is the greater number."}

After adding the response to the HTML numeric-check, directive does not work and it allows us to enter all characters instead of only numeric values.

Sushil Sharma
  • 2,321
  • 3
  • 29
  • 49
Rochak
  • 28
  • 3

1 Answers1

0

Have you tried to put something like:

app.directive('numericCheck', function () {
return {
    link: function (scope, element, attr) {
        element.on('keypress', function (event) { 
scope.$apply(function(){ 
            event = (event) ? event : window.event;
            if(/Firefox/.test(window.navigator.userAgent) && event.keyCode!=0) {
                return true;
            }
            var charCode = (event.which) ? event.which : event.keyCode;
            if (charCode > 31 && charCode != 46 && charCode != 47 && charCode != 45 && (charCode < 48 || charCode > 57) || (charCode==45 && (event.target.selectionStart!=0 || event.target.value.indexOf('-')>=0)) || (charCode==46 && event.target.value.indexOf('.')>=0) || (charCode==47 && (event.target.selectionStart==0 || event.target.value.indexOf('/')>=0))) {
                return false;
            }
            return true;
});
        });  
    }

};

federico scamuzzi
  • 3,708
  • 1
  • 17
  • 24