function maybeUpdateEndField(start_date_field: HTMLInputElement) { let end_date_field: HTMLInputElement | null | undefined = start_date_field ?.closest(".form-row") ?.querySelector(".field-end .vDateField"); if (end_date_field && !end_date_field.value) { end_date_field.value = start_date_field.value; } } function setupListeners(element: ParentNode) { for (let start_date_field of element.querySelectorAll( "#meeting_times-group .field-start .vDateField", ) as NodeListOf) { start_date_field.addEventListener("change", () => { maybeUpdateEndField(start_date_field); }); // element is focused after selecting a date using Django's DateTimeShortcuts start_date_field.addEventListener("focus", () => { maybeUpdateEndField(start_date_field); }); } } $(() => setupListeners(document)); $(document).on("formset:added", (event) => setupListeners(event.target));