Skip to content Skip to sidebar Skip to footer

2 States Roundable Numeric Text Box With Knockoutjs

I want to have an html numeric text box with 2 states, when focused, it has to show all decimal places, and when focus is lost, only show 2 decimals. I've almost achieved it. HTML:

Solution 1:

You're mixing in too much jQuery :)

Knockout has event bindings and a hasFocus binding to deal with UI input.

In the example below I've made a viewmodel that has a hidden realValue observable which stores the unmodified input. The displayValue limits this number to a 2 digit number when showDigits is false.

I've used hasFocus to track whether we want to show the whole number: it's linked to showDigits.

varViewModel = function() {
  this.showDigits = ko.observable(true);
  
  var realValue = ko.observable(6.32324261);

  this.displayValue = ko.computed({
    read: function() {
      returnthis.showDigits() 
        ? realValue()
        : parseFloat(realValue()).toFixed(2);
    },
    write: realValue
  }, this);
};


ko.applyBindings(newViewModel()); 
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script><inputdata-bind="value: displayValue, hasFocus: showDigits"type="number"/>

Edit: After comment that a computed is too much extra code: here's how to wrap the computed logic in a reusable extender:

ko.extenders.digitInput = function(target, option) {
  var realValue = target,
      showRealValue = ko.observable(false),
      displayValue = ko.computed({
        read: function() {
          returnshowRealValue() 
            ? realValue()
            : parseFloat(realValue()).toFixed(2);
        },
        write: realValue
      }, this);
  
  displayValue.showRealValue = showRealValue;
  
  return displayValue;
};


varViewModel = function() {
  this.value1 = ko.observable(6.452345).extend({ digitInput: true });
  this.value2 = ko.observable(4.145).extend({ digitInput: true });
};


ko.applyBindings(newViewModel());
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script><inputdata-bind="value: value1, hasFocus: value1.showRealValue"type="number"/><inputdata-bind="value: value2, hasFocus: value2.showRealValue"type="number"/>

Post a Comment for "2 States Roundable Numeric Text Box With Knockoutjs"