0

Problem:

I've been recently requested the feature of having the keypad period be replaced with a comma when inserting a number in a field in my spa application built with angular. I decided to go with the directive approach to be able to easily reuse it in the future and had a partial success with it, but it works only on

input type="text"

When trying the same solution on

input type="number"

the field get reset and I get the following error:

ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.js:3501 The specified value "12," is not a valid number. The value must match to the following regular expression: -?(\d+|\d+.\d+|.\d+)([eE][-+]?\d+)?

but when I type, for example, 12, no error is raised.

Any idea on why and how to get it to work on number input?

Code:

'use strict';

myApp.directive('replaceKeypadComma', function() {
    return {
        restrict: 'A',
        link: function($scope, element, attrs, controller) {
            element.on('keydown', function(event) {
                if (event.keyCode == 110) {
                    element.val(element.val() + ',');
                    event.preventDefault();
                }
            });
        }
    }
});

Working Plunker with text input:

https://plnkr.co/edit/hBThZOI1T4rk3cbwRscq

Broken Plunker with number input:

https://plnkr.co/edit/zBqwWmZ0iAhIH728ZeCh

P. Moloney
  • 721
  • 8
  • 22
vkmi
  • 23
  • 7
  • Your plnkr works as expected for me, using both chrome 60.0.3112.90, and Firefox 54.0.1... – P. Moloney Aug 03 '17 at 11:38
  • The working plunker refers to text input. Here a plunker referring to a number input, not working as intended: https://plnkr.co/edit/zBqwWmZ0iAhIH728ZeCh – vkmi Aug 03 '17 at 14:16

1 Answers1

1

input type="number" is allowed to contain only a "floating point number" so doesn't allow commas.

Some browsers do accept input containing a decimal comma and transform it into a decimal period, depending on the user's or page's locale, but enough of them don't do this that it's probably best to avoid input type="number" if you need to support decimal-comma numbers.

Daniel Beck
  • 20,653
  • 5
  • 38
  • 53