How to bind HTML5 datepicker and other input types using Knockout.js?

I started to learn knockout.js and faced some issues while working with html5 form fields. When I am dealing with html5 input field elements which have text type then everything goes well, but unfortunately I cannot get and display values from html5 datepicker which type is date.

I found some examples that describe data-binding with datepickers in KnockoutJS, but they use some other sources (for example moment.js or jQuery UI) in order to achieve needed result.

Therefore could you give me any idea about binding html5 datepicker inputs with KnockoutJS without including any additional plugins and libraries, and without using computed variables?

Apart from that, I even did not find any references in KO’s official documentation that explain how to work with HTML5’s new input types such as color, email, url, number, range and some others. Therefore, I would highly appreciate if you could give me any hint.

<h2>Set date</h2>
<!--input type "text" works well and the result is visible below whereas other input types are problematic-->
<input type="text" data-bind="value: addStart" /><br> 

From <input  type="date" data-bind="date: addStartDate" /> 
To <input type="date" data-bind="date: addEndDate" />

<input  type="color" data-bind="date: addColor" /> 
<input type="email" data-bind="date: addEmail" />
<input type="url" data-bind="date: addUrl" />
<input type="number" data-bind="date: addNumber" />
<input type="range" data-bind="date: addRange" />

<h2>Display date</h2>   
<strong data-bind="text: addStart" ></strong><br> 
<strong data-bind="text: timeLine" ></strong><br> 

<strong  type="color" data-bind="date: addColor"></strong> <br> 
<strong type="email" data-bind="date: addEmail"></strong><br> 
<strong type="url" data-bind="date: addUrl"></strong><br> 
<strong type="number" data-bind="date: addNumber"></strong><br> 
<strong type="range" data-bind="date: addRange"></strong><br>
var ViewModel = function() {
    var self = this;
    self.addStart = ko.observable();       
    self.addStartDate = ko.observable();  // date
    self.addEndDate = ko.observable();    // date

    self.addColor = ko.observable();    // Color
    self.addEmail = ko.observable();    // Email
    self.addUrl = ko.observable();      // Url
    self.addNumber = ko.observable();   // Number
    self.addRange = ko.observable();    // Number

};
// Activates knockout.js
ko.applyBindings(new ViewModel());


Source: cross-browser

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.