Skip to content Skip to sidebar Skip to footer

Dependant Combo Boxes

On a webpage, I have two combo boxes. The first has start times (hourly) from 9am to 9pm. The second has end times from 10am - 12pm. The user selects a start time and an end time.

Solution 1:

Anything is possible in the magical world of software, not only can it be done but there are many different ways of achieving it.

Here is a rough example: https://jsfiddle.net/n6fm39ww/

HTML

<selectname="start_time"></select><selectname="end_time"><optionvalue="default">Pick a start time</option></select>

JS

// Add each option to start_timesfor (var hour = 9; hour <= 21; hour++) {
  var option = "<option value='"+hour+"'>"+hour+"</option>";
    $('[name="start_time"]').append(option);
}

// When the start time is changed, set the end time
$('[name="start_time"]').on('change', function() {
    // This is the start time chosenvar start_time = $(this).val();
  // Remove the default option
  $('[name="end_time"]').find('option').remove();
  // Add options after the start timefor (var hour = parseInt(start_time) + 1; hour <= 24; hour++) {
      var option = "<option value='"+hour+"'>"+hour+"</option>";
    $('[name="end_time"]').append(option);
  }
});

Solution 2:

Please make sure to provide code samples in the future.

Here is an example of how that is done: https://jsfiddle.net/c6432wee/


Say we have two selects.

<select id="startTime"> <option value="na">Please Select A Time</option> <option value=1>1:00PM</option> </select>

<select id="endTime"> <option value="na">Please Select A Time</option> <option value=1>1:00PM</option> </select>

We start by setting the end time hidden

$('#endTime').css('display', 'none');

Then we register an event handler. Everytime it is changed, we look at the value to see if it different from our default placeholder.

  $('#startTime').change(function () {
    if($('#startTime').val() !== 'na') {
      $('#endTime').css('display', 'initial');
    }
  });

If it is, we set endTime back to its initial display state.

$('#endTime').css('display', 'initial');

Post a Comment for "Dependant Combo Boxes"