Search code examples
javascripthtmlknockout.jshtml-input

HTML text input not updating with Knockout Bindings


I am trying to automatically add slashes for a DOB input field but Knockout bindings are not playing nice.

<input 
name=x 
size=10 
maxlength=10 
class="span12" 
placeholder="Date of birth (MM/DD/YYYY)"
  onkeyup="this.value=this.value.replace(/^(\d\d)(\d)$/g,'$1/$2').replace(/^(\d\d\/\d\d)(\d+)$/g,'$1/$2').replace(/[^\d\/]/g,'')"
  data-bind="value:visitor().dateOfBirth, valueUpdate:'keyup'" />

The issue now is that the Knockout Js bindings are not allowing the slashes value to be automatically updated. When I enter dates in the text box no slashes show up. How do I set up a subscriber for myViewModel to modify the value whenever it changes?


Solution

  • You should do something along these lines - note you should remove the inlined onkeyup from your input tag and let your view model handle it:

    var vm = function () {
      var self = this;
      self.dateOfBirth = ko.observable();
      self.insertSlashes = function () {
         var currentValue = self.dateOfBirth();
         self.dateOfBirth(currentValue
            .replace(/^(\d\d)(\d)$/g,'$1/$2')
            .replace(/^(\d\d\/\d\d)(\d+)$/g,'$1/$2')
            .replace(/[^\d\/]/g,'')
        );
      }
    }
    ko.applyBindings(new vm());
    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
    <input 
      placeholder="Date of birth (MM/DD/YYYY)"
      data-bind="value: dateOfBirth, valueUpdate:'keyup', event: { keyup: insertSlashes } " 
    />