Search code examples
knockout.jsknockout-mapping-plugin

Knockoutjs treats input text as number


I'm using mapping plugin. I have a list of customer data. One of the properties is percent amount (int). However when I update the value of the text box the new percent property shows up as a string. How do I make it so that the mapping plugin updates percent property as an int.

thanks


Solution

  • you could expose the field as a writable computed value:

    var Model = function() {
      var self = this;
      self.percentProp = ko.observable();
      self.percentPropComputed = ko.computed({
        read: function() {
          return self.percentProp();
        },
        write: function(newValue) {
          if( !isNaN(newValue) ) {
            self.percentProp(parseInt(newValue));
          }
      });
    };
    

    html:

    <input type="number" data-bind="value: percentPropComputed" />