Gericke
Gericke

Reputation: 2241

Bind bootstrap datepicker with knockoutjs

I want to use a bootstrap datepicker and to bind the selected date with knockoutjs.

the function that uses the datepicker:

$(function() {

    // create the departure date
    $('#depart-date').datepicker({
        autoclose: true,
        format: 'yyyy/mm/dd',
    }).on('changeDate', function(ev) {
        ConfigureReturnDate();
    });


    $('#return-date').datepicker({
        autoclose: true,
        format: 'yyyy/mm/dd',
        startDate: $('#depart-date').val()
    });

    // Set the min date on page load
    ConfigureReturnDate();

    // Resets the min date of the return date
    function ConfigureReturnDate() {
        $('#return-date').datepicker('setStartDate', $('#depart-date').val());
    }

});

Here is a fiddle that I want to use but is not sure how to go about doing so. http://jsfiddle.net/zNbUT/276/

Upvotes: 10

Views: 10759

Answers (2)

Jacques Bronkhorst
Jacques Bronkhorst

Reputation: 1695

I also used bootstrap-datepicker.js but in a different way:

My Viewmodel:

 var MyDataViewModel = {
     //Set Todays Date
     StartDate: ko.observable(new Date())
 }

My HTML:

<div id="dtpDate" class="input-append">
    <input required="required" id="txtdtpDate" data-format="yyyy-MM-dd" type="text" style="width: 75%;" />
    <span class="add-on"><i data-time-icon="icon-time" data-date-icon="icon-calendar"></i>
    </span>
</div>

And the JS to make it function:

$(function () {
    $('#dtpDate').datetimepicker({
        pickTime: false
        })
        .on('changeDate', function (ev) {
            //Date.Subtring(1,10) for formatting purposes
            MyDataViewModel.StartDate(ko.toJSON(ev.date).substr(1, 10));
        });
    });
});

And this works perfectly for me

Upvotes: 3

Gericke
Gericke

Reputation: 2241

I found a fiddle that will help me http://jsfiddle.net/jearles/HLVfA/6/

Functionality from the fiddle:

  ko.bindingHandlers.datepicker = {
        init: function (element, valueAccessor, allBindingsAccessor) {
            //initialize datepicker with some optional options
            var options = allBindingsAccessor().datepickerOptions || {};
            $(element).datepicker(options).on("changeDate", function (ev) {
                var observable = valueAccessor();
                observable(ev.date);
            });
        },
        update: function (element, valueAccessor) {
            var value = ko.utils.unwrapObservable(valueAccessor());
            $(element).datepicker("setValue", value);
        }
    };

Upvotes: 5

Related Questions