knockout.jscustom-binding

Dynamic currency format on input field


I would like to ask you is it possible to format dynamically input value?
So when I'm entering some value it will dynamically add commas to format currency.
For example I'm writing 1234 and it will be formatted to 1'234 dynamically.
If I delete one number it will be changed to 123.
I'm thinking about some custom binding. But is it possible to add a rule for every change?

Cheer


Solution

  • I already write what I need :)

    Here is my working JSFiddle

    And my code:

    function TestViewModel() {
      var self = this;
      self.myCurrency = ko.observable();
    }
    
    ko.bindingHandlers.currencyFormat = {
      init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        ko.utils.registerEventHandler(element, 'keyup', function (event) {
            var observable = valueAccessor();
            observable(formatInput(element.value));
            observable.notifySubscribers(5);
        });
      },
      update: function (element, valueAccessor, allBindingsAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        $(element).val(value);
      }
    };
    
    function formatInput(value) {
      value += '';
    
      value = value.replace(/,/g, '');
      var rgx = /(\d+)(\d{3})/;
      while (rgx.test(value)) {
        value = value.replace(rgx, '$1' + ',' + '$2');
      }
    
      return value;
    }
    
    $(document).ready(function () {
      ko.applyBindings(new TestViewModel());
    });
    

    Enjoy it