1

Is there an easy way to use data-bind="textInput: aProperty" and add an input mask or some automatic formatting as the user types?

Using the masked input plugin kind of works, but I lose the "as-you-type" updates that Knockout's "textInput:" provides, so other parts of the script only see the change after the field loses focus (effectively behaving as a plain old "value:" binding in Knockout).

A naïve solution with a computed observable that does the formatting doesn't work because each keystroke to a field that updates itself changes the input focus to somewhere else in the page, so the user can't keep typing.

Can I make these two libraries play nice with each other or should I make my custom solution? They do a lot of things in their event handlers to be compatible with all browsers, so it's not a surprise that it's hard to make them work together, but that is also exactly why I don't want to fiddle with all those keyup, input, change, events by myself.

All previous answers on StackOverflow don't mind propagating the changes only after the field loses focus. Maybe those answers were posted before textInput was added to Knockout, so there wasn't anything better at the time. That's why I'm asking a new question.

marcus
  • 5,041
  • 3
  • 30
  • 36

1 Answers1

4

I've written a fiddle that uses just a computed observable, and I don't have a focus problem with it. Does this work as you expect?

var displayString = ko.observable('');
var formattedString = ko.computed({
    read: function () {
        return displayString();
    },
    write: function (newValue) {
        var f = format(newValue);
        console.debug("Format", newValue, "=", f);
        displayString(f);
    }
});

http://jsfiddle.net/csmmnq25/

Roy J
  • 42,522
  • 10
  • 78
  • 102
  • It looks like you can't add anything at the end (such as “.00”) without moving the cursor and messing everything up (including Backspace). This is not exactly the same behavior I was seeing before, but it seems to be related. – marcus May 25 '15 at 16:52
  • Every time the value gets rewritten, the cursor is positioned at the end. This is fine if you're adding to the end, but a problem if you're editing in the middle. Positioning the cursor within the field could be tricky, depending on the formatting. – Roy J May 25 '15 at 19:39
  • I guess the focus problem I had is related to KO's foreach (I have multiple inputs in a table). I will use your solution when my form doesn't loop and I don't expect the user to insert something in the middle (and any number will require editing in the middle if I keep adding cents automatically after each keystroke...) – marcus May 25 '15 at 19:55
  • OK, my focus problem occurs when I use a combination of foreach AND template. Probably this deserves another question (or a bug report...) – marcus May 25 '15 at 22:04