Copy the previous time into next-added time when entering multivalue datetime fields in Drupal 8 and 9

For editor convenience, the site should assume that times will stay the same even as dates change for multi-day events.

javascript remove last element of an array jquery get id

This is a bit ugly, but it works, and it’s not nearly as ugly as some of the paths i went down.

/**
 * @file
 * Copy time value when adding an additional date.
 */

(function ($, Drupal) {

  $(document).ajaxComplete(function(event, request, settings) {
    // We could make this run slightly less often by drilling down into this object.
    // request.responseJSON[0]
    // specifically for:​
    // settings: ajax: callback: Array [ "Drupal\\datetime_range\\Plugin\\Field\\FieldWidget\\DateRangeDefaultWidget", "addMoreAjax" ]
    var contestants = $('[name^="field_findit_dates["][name$="][value][time]"]');
    var endtime_contestants = $('[name^="field_findit_dates["][name$="][end_value][time]"]');
    var last_time = '';
    contestants.each(function() {
      var name = $(this).attr('name');
      if (last_time && !$(this).val()) {
        $(this).val(last_time);
      }
      last_time = $(this).val();
    });
    var last_time = '';
    endtime_contestants.each(function() {
      var name = $(this).attr('name');
      if (last_time && !$(this).val()) {
        $(this).val(last_time);
      }
      last_time = $(this).val();
    });
  });

})(jQuery, Drupal);