0

I have this code that changes the format of dates. I would like to know how can I make ISO format the default so that every time someone picks a date it gets formatted in ISO8601 yy-mm-dd format without needing to select again. This is because it only assumes the format if I select another option then go back to the previous.

<script>
  $(function() {
    $("#datepicker").datepicker();
    $("#format").on("change", function() {
      $("#datepicker").datepicker("option", "dateFormat", $(this).val());
    });
  });
</script>
<p>
  Date: <input type="text" id="datepicker" size="30">
</p>
<p>
  Format options:<br>
  <select id="format">
    <option value="yy-mm-dd" selected>ISO 8601 - yy-mm-dd</option>
    <option value="d M, y">Short - d M, y</option>
  </select>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Luthermilla Ecole
  • 666
  • 1
  • 6
  • 14
  • Please add the required $.datepicker lib in your snippet so we can run your code example. – connexo Jul 31 '20 at 08:07
  • 1
    Does this answer your question? [jQuery UI DatePicker - Change Date Format](https://stackoverflow.com/questions/1328025/jquery-ui-datepicker-change-date-format) – FluffyKitten Jul 31 '20 at 08:11

1 Answers1

1

To do what you require set the dateFormat in the initialisation options based on the default value of the select:

$(function() {
  let $datepicker = $("#datepicker");
  let $format = $('#format');

  $datepicker.datepicker({
    dateFormat: $format.val()
  });

  $format.on("change", function() {
    $datepicker.datepicker("option", "dateFormat", this.value);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" />
<p>
  Date: <input type="text" id="datepicker" size="30">
</p>
<p>
  Format options:<br>
  <select id="format">
    <option value="yy-mm-dd" selected>ISO 8601 - yy-mm-dd</option>
    <option value="d M, y">Short - d M, y</option>
  </select>
</p>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339