The Firmhouse Logo [FH]
Developer Docs

On Checkout show available delivery dates based on chosen city

This example shows you how you can use the value from a dropdown that contains cities, to modify available delivery dates in a datepicker.

Firmhouse provides you the option to create additional Extra Fields so that you can ask additional extra information from your customers on checkout.

For example, some of our users use this for asking someone's age, the name of their pet, or when and where they would like to have their products delivered.

In the following sample we will be using the value of an extra field called "Nearest city" in combination with a datepicker field "Request delivery date". We'll make the available dates in the "Request delivery date" datepicker field dependent on which city which was chosen.

For example: for Amsterdam only enable Mondays, and for Rotterdam only enable Tuesdays and Wednesdays.

Sample code

Put this in the <body> in Checkout > Preferences > Custom code.

You need to update the ids of the extra fields in the document.querySelector() calls and you need to customise the city -> day mappings in the availableShipmentDates variable.

<script> 
  const availableShipmentDates = {
      Amsterdam: [1],
      Rotterdam: [2, 3],
  }; 

  const citySelector = document.querySelector("#subscription_extra_field_answers_attributes_3_value"); 
  citySelector.addEventListener("change", updateShipmentDate);

  function updateShipmentDate(event) {
    console.debug("updating available shipment dates...")
    const shipmentDate = document.querySelector("#subscription_extra_field_answers_attributes_4_value"); 
    
    const datesForCity = availableShipmentDates[event.target.value]
    if (datesForCity) {
      shipmentDate._flatpickr.config.disable = [
        function (date) {
          // Disable all dates between now and next week.
          const today = new Date()
          const nextWeek = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 7)
          if (date <= nextWeek) {
            return true;
          }

          // Make days available that are in listed cities.
          if (datesForCity.includes(date.getDay())) {
            return false;
          }

          // Make all other dates unavailable.
          return true;
        } 
      ];
    } else {
      shipmentDate._flatpickr.config.disable = [
        function (date) {
          return true;
        } 
      ];
    }
    shipmentDate._flatpickr.clear()
  }

  document.addEventListener("DOMContentLoaded", function(event) {
    const citySelector = document.querySelector("#subscription_extra_field_answers_attributes_3_value"); 
    if (citySelector) {
      citySelector.dispatchEvent(new Event('change', { 'bubbles': true }))
    }
  })
</script>