Dynamically Generate a Time Select Dropdown with Intervals (Javascript or jQuery)

Dynamically generating HTML elements based on user input or specific conditions is a common requirement in web development. One such scenario is creating time dropdowns that adjust their options based on the current time, desired range, and intervals. This article presents a JavaScript or jQuery solution for creating dynamic time dropdowns within a select form element.

Why Dynamic Time Dropdowns?

Dynamic time dropdowns are helpful in many situations:

Dynamic Time Solution Using JavaScript

The JavaScript solution below enables you to create dynamic time dropdown menus on your web pages. These menus adapt to different scenarios and provide users with relevant time choices.

Here’s what it offers:

This solution enhances user experience by presenting only relevant time choices, eliminating unnecessary scrolling and making interactions smoother. Whether you’re building a scheduling application, a booking system, or any other feature that requires time selection, this JavaScript code provides the flexibility and control you need.

Dynamic Time Examples

<select class="timeSelect" data-from="" data-to="" data-interval="30" data-start-now="false" data-format="H:i"></select>
<select class="timeSelect" data-from="" data-to="" data-interval="30" data-start-now="false" data-format="H:i"></select>
<select class="timeSelect" data-from="10" data-to="now" data-interval="60" data-start-now="false" data-format="H:i">
<select class="timeSelect" data-from="14" data-to="18" data-interval="10" data-start-now="false" data-format="h:i a"></select>
<select class="timeSelect" data-from="" data-to="23" data-interval="15" data-start-now="true" data-format="H:i">
</select>

Dynamic Time JavaScript

Here’s the complete JavaScript code for creating dynamic time dropdowns:

function getTime(from, to, interval, startNow, format, timeSelect) { 
  var select = '<option value="">Select a Time</option>';
  var now = new Date();
  var currentHour = now.getHours();
  var currentMinute = now.getMinutes();
  var optionsCount = 0; 

  if (from === "now") {
    from = currentHour;
  } else if (from === "") {
    from = 0; 
  } else {
    from = parseInt(from);
  }

  if (to === "now") {
    to = currentHour;
  } else if (to === "") {
    to = 23; 
  } else {
    to = parseInt(to);
  }

  if (startNow) {
    if (from < currentHour) {
      from = currentHour;
    }
    if (to < currentHour) {
      to = currentHour; 
    }
  }

  for (var hour = from; hour <= to; hour++) {
    var hour12 = hour > 12 ? hour - 12 : hour;
    hour12 = hour12 === 0 ? 12 : hour12; // Change 0 to 12 for 12 AM
    var ampm = hour >= 12 ? 'PM' : 'AM';
    for (var min = 0; min < 60; min += interval) {
      if (startNow && hour === currentHour && min < currentMinute) {
        continue;
      }
      var min0 = min < 10 ? '0' + min : min;

      var date = new Date();
      date.setHours(hour);
      date.setMinutes(min);
      var value = formatDate(date, format);

      select += '<option value="' + value + '">' + hour12 + ':' + min0 + ' ' + ampm + '</option>';
      optionsCount++; 
    }
  }

  timeSelect.innerHTML = select;
  if (optionsCount <= 1) { 
    timeSelect.disabled = true;
  }
}

function formatDate(date, format) {
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var ampm = hours >= 12 ? 'PM' : 'AM';
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour '0' should be '12'
  minutes = minutes < 10 ? '0'+minutes : minutes;
  var strTime = hours + ':' + minutes + ' ' + ampm;
  return format
    .replace(/H/g, date.getHours())
    .replace(/h/g, hours)
    .replace(/i/g, minutes)
    .replace(/s/g, date.getSeconds())
    .replace(/a/g, ampm.toLowerCase())
    .replace(/A/g, ampm);
}

var timeSelects = document.querySelectorAll('.timeSelect');

timeSelects.forEach(function(timeSelect) {
  var from = timeSelect.dataset.from; 
  var to = timeSelect.dataset.to;     
  var interval = parseInt(timeSelect.dataset.interval);
  var startNow = timeSelect.dataset.startNow === 'true';
  var format = timeSelect.dataset.format;

  getTime(from, to, interval, startNow, format, timeSelect); 
});

Breaking Down the Code

Now, let’s break down the code for our readers:

1. HTML Structure:

2. JavaScript Functions:

3. Initialization:

Dynamic Time jQuery

If you’re utilizing jQuery, here’s the solution rewritten.

function getTime(from, to, interval, startNow, format, $timeSelect) {
  var selectOptions = '<option value="">Select a Time</option>';
  var now = new Date();
  var currentHour = now.getHours();
  var currentMinute = now.getMinutes();
  var optionsCount = 0; 

  if (from === "now") {
    from = currentHour;
  } else if (from === "") {
    from = 0; 
  } else {
    from = parseInt(from);
  }

  if (to === "now") {
    to = currentHour;
  } else if (to === "") {
    to = 23; 
  } else {
    to = parseInt(to);
  }

  if (startNow) {
    if (from < currentHour) {
      from = currentHour;
    }
    if (to < currentHour) {
      to = currentHour; 
    }
  }

  for (var hour = from; hour <= to; hour++) {
    var hour12 = hour > 12 ? hour - 12 : hour;
    hour12 = hour12 === 0 ? 12 : hour12; 
    var ampm = hour >= 12 ? 'PM' : 'AM';
    for (var min = 0; min < 60; min += interval) {
      if (startNow && hour === currentHour && min < currentMinute) {
        continue;
      }
      var min0 = min < 10 ? '0' + min : min;

      var date = new Date();
      date.setHours(hour);
      date.setMinutes(min);
      var value = formatDate(date, format);

      selectOptions += '<option value="' + value + '">' + hour12 + ':' + min0 + ' ' + ampm + '</option>';
      optionsCount++; 
    }
  }

  $timeSelect.html(selectOptions);
  if (optionsCount <= 1) { 
    $timeSelect.prop('disabled', true);
  }
}

function formatDate(date, format) {
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var ampm = hours >= 12 ? 'PM' : 'AM';
  hours = hours % 12;
  hours = hours ? hours : 12; 
  minutes = minutes < 10 ? '0'+minutes : minutes;
  var strTime = hours + ':' + minutes + ' ' + ampm;
  return format
    .replace(/H/g, date.getHours())
    .replace(/h/g, hours)
    .replace(/i/g, minutes)
    .replace(/s/g, date.getSeconds())
    .replace(/a/g, ampm.toLowerCase())
    .replace(/A/g, ampm);
}

$(document).ready(function() {
  $('.timeSelect').each(function() {
    var $timeSelect = $(this);
    var from = $timeSelect.data('from'); 
    var to = $timeSelect.data('to');     
    var interval = parseInt($timeSelect.data('interval'));
    var startNow = $timeSelect.data('start-now') === true;
    var format = $timeSelect.data('format');

    getTime(from, to, interval, startNow, format, $timeSelect); 
  });
});

This approach allows multiple time dropdowns on the same page, each with its configuration and behavior. The code handles various scenarios, including full-day selections, starting from the current time and different time formats, providing a flexible and user-friendly solution for dynamic time selection.

Exit mobile version