Using Knockout.js how do bind a Date property to a HTML5 date picker?

后端 未结 8 692
南旧
南旧 2021-01-04 00:37

(this only works in Chrome at the moment as most browsers don\'t yet implement date picker for input type=\"date\")

In the following example MyDate starts o

8条回答
  •  盖世英雄少女心
    2021-01-04 01:21

    You can use the computed vartiable for the date object in your model:

    In html:

    
    

    In code:

    var currentDate = (new Date()).toISOString().split('T')[0];
    
    // this is used instead of MyDate in the data binding
    rawDate : ko.observable(currentDate),
    
    ...
    // and then set up the dependent variable
    viewModel.MyDate = ko.computed(function () {
        var val = this.rawDate();
        if (typeof val === 'string') val = new Date(val);
    
        return val;
    }, viewModel)
    

    Please see the demo: http://jsfiddle.net/gcAXB/1/

提交回复
热议问题