vkmi
vkmi

Reputation: 23

Replacing keypad period with comma in an input (type=number) with an angular directive

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

Upvotes: 0

Views: 1486

Answers (1)

Daniel Beck
Daniel Beck

Reputation: 21514

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.

Upvotes: 1

Related Questions