Blue
Blue

Reputation: 611

backbone models and datepicker default date

I want to display a default date in a html datepicker, like this:

<input class="topcoat-text-input"id="birthday" type="date" name="birthday" value= "<%=birthday%>"/>

where <%=birthday%> shall be the birthday value in my backbone model, that i defined as this:

model = Backbone.Model.extend({
        defaults: {
            birthday: new Date(1984, 01, 01),
        }

I then have a view that gets the html template, injects the model as JSON and displays it. This works with everything else, but not the date. The datepicker can not display this data and just shows dd/mm/yyyy instead. How can i get it to show the date i set as default?

Upvotes: 0

Views: 1083

Answers (2)

Elad Levy
Elad Levy

Reputation: 301

You need to parse the Date object before setting it in your model. You can do it in the initialize method like so:

model = Backbone.Model.extend({
        initialize: function() {
            if(!this.has('birthday')) {
                var defaultDate = new Date(1984,01,10);
                //Notice the months are zero based so you need to +1
                var date = (defaultDate.getMonth() + 1) + '/' + defaultDate.getDate() + '/' + defaultDate.getFullYear();
                this.set('birthday', date);
            }      
        }
});

This should set the date as a string that the HTML date input can handle

Upvotes: 2

eck
eck

Reputation: 1125

The default Date.toString() method is outputting in a format that a date field does not accept. You'll need to write out the string more specifically.

<% birthday = new Date(birthday) %>
<input class="topcoat-text-input"id="birthday" type="date" name="birthday" value= "<%=birthday.getDate() + "-" + birthday.getMonth() + "-" + birthday.getFullYear()%>"/>

Haven't tested if that's syntactically correct, but I think you get the idea.

Upvotes: 0

Related Questions