Search code examples
knockout.jsmaskedtextbox

Is it possible to use KnockoutJS with a masked input?


I´m using that plugin : https://github.com/plentz/jquery-maskmoney to format my money editor...

I tried to use KnockoutJS in that editor, but it does not work... Without that mask all works fine...

My code test is simple :

<input id="Price" data-bind="value: Price"  type="text"  name="Price"> 

Javascript to Mask input

$("#Price").maskMoney({ symbol: 'R$ ', showSymbol: true, thousands: '.', decimal: ',', symbolStay: false });

And KnockoutJS

var ViewModel = function () {
            this.Price = ko.observable();

            this.PriceFinal= ko.computed(function () {
                return this.Price() 
            }, this);
        };

        ko.applyBindings(new ViewModel()); 

Solution

  • You should use a writable computed observable.

    function MyViewModel() {
        this.price = ko.observable(25.99);
    
        this.formattedPrice = ko.computed({
            read: function () {
                return '$' + this.price().toFixed(2);
            },
            write: function (value) {
                // Strip out unwanted characters, parse as float, then write the raw data back to the underlying "price" observable
                value = parseFloat(value.replace(/[^\.\d]/g, ""));
                this.price(isNaN(value) ? 0 : value); // Write to underlying storage
            },
            owner: this
        });
    }
    
    ko.applyBindings(new MyViewModel());