Search code examples
backbone.js

Backbone.js date input - set date picker default year in the <input /> tag


I am working on a Backform displaying a date input where the user must input it's birthdate. When giving focus to this input, a date picker is shown.

Our users (and I) are not getting any younger, and it's getting really tedious to scroll from the current date to our actual birthyear.

Here is a simplified version of the form :

this.form = new Backform.Form({
  el:$('.Host-form'),
  model: new HostModel({
    birthdate: '',
  }, {
    birthdate: {
      type: "date",
      mandatory: true,
      readonly: false
    }
  }),
  fields: {
    "name": "birthdate",
    "label": "Birthdate *",
    "control": "input",
    "placeholder": "Birthdate *",
    "disabled": false,
    "required": true,
    "value": null,
    "options": [],
    "extraClasses": [],
    "type": "date"
  },
});

I already managed to set a default date to the input by adding value attribute but that is not quite what I want to achieve.

Is there a way to set a default year in the past by adding an attribute in the tag ?


Solution

  • Since the date picker was in fact a html <input type="date" />, I managed to solve this issue with this :

    var m = moment().subtract(18, 'years');
    
    $('[name="birthdate"]').attr('max', m.format('YYYY-MM-DD'));
    $('[name="birthdate"]').attr('value', m.format('YYYY-MM-DD'));
    

    First line will prevent user to select a date after specified date. Second line will select the last selectable date.