tortuga
tortuga

Reputation: 414

Knockout.js - Forcing input to be numeric - allow dot and comma notation

To better understand, pls go to http://knockoutjs.com/documentation/extenders.html and have a look at Live Example 1: Forcing input to be numeric

I can enter a decimal value with a . (dot) but not with a comma. Then the amount jumps to 0.

Any idea how I can allow dot AND comma? I would like to allow input like 20.00 and 20,00

Kind regards,

K.

Upvotes: 2

Views: 3703

Answers (2)

Stas Slabko
Stas Slabko

Reputation: 516

You may not only want to accept numeric fields with comma, but also output numbers from you VM with comma as decimal point. Thus, you need also to implement read getter function of the underlying computed observable. Also write function could be simplified if you don't care about rounding. Here is the full code:

ko.extenders.numeric = function(target) {
    var result = ko.computed({
        read: function() {
            var value = target();
            return isNaN(value) || value===null || value===''
                ? value
                : value.toString().replace('.',',');
        }
        ,write: function(newValue) {
            if (typeof newValue === "string") {
                newValue = newValue.replace(",", ".");
            }
            if (newValue !== target()) {
                target(newValue);
            }
        }
    });
    result(target());
    return result;
};  

Upvotes: 1

Bram De Moor
Bram De Moor

Reputation: 186

You could implement a small fix in the numeric extender (ref. the extenders documentation page that you posted) to solve this. In the "write" method of the extender, add the following code on top:

        if (typeof newValue == "string") {
            newValue = newValue.replace(",", ".");
        }

The if-statement is needed to prevent an error on model initialization. When the model is first created, the value is most likely set to a number instead of a string, so we can't call the .replace method on this object.

Upvotes: 0

Related Questions