Set default value for datepicker using jQuery in Drupal

Datepicker in drupal is rendered as separate select elements for day, month and year by default which makes it difficult to set a default value if we want to set it to some string value, eg. today, +2 months, etc. This page is to check how we can set default value for datepicker using a simple jQuery.

Get string from PHP

Consider you have the above string value. If you are sending this value from a php code, convert it to a date format using strtotime().

$dateFormattedValue = date('Y-m-d', strtotime('today'));

The $dateFormattedValue will be retrieved as 2018-02-21. Use it in the js code to set the default value for your date picker element which displays like - 

datepicker

Set default value for datepicker jQuery

To set a default value, we need to loop into each element and set its value fetching the date parts from the string received from PHP. For eg -

var dateVal = value_from_php or a string value as "2018-02-21";

$('div.form-item.webform-component', '.webform-client-form-' + nid).each(function() {
  //Check if our element is of type date.
  if ($el.hasClass('webform-component-date')
    var $el = $(this);
    var date = dateVal.split('-');
    //Assign value to each select element - year, month and day
    $el.find('select.year, input.year').val(+date[0]);
    $el.find('select.month').val(+date[1]);
    $el.find('select.day').val(+date[2]);
  }
});

If you're not using this in the webform, we can directly set the default value from the code inside the if() loop. 

Note that webform also allows you to set the default value of a field from the component setting. We can make use of the above snippet to override it to some another value in any case.