如何使用JS/jQuery验证两个下拉字段中的时间值

How to validate time values in two dropdown fields against each other using JS/jQuery?

本文关键字:两个 字段 时间 JS 何使用 jQuery 验证      更新时间:2023-10-10

我有一个包含时间值的"From"answers"To"下拉列表的窗体。它看起来像这样:

From
<select class="from">
<option value="09:00 AM">09:00 AM</option>
<option value="10:00 AM">10:00 AM</option>
<option value="10:15 AM">10:15 AM</option>
<option value="10:30 AM">10:30 AM</option>
<option value="10:45 AM">10:45 AM</option>
<option value="11:00 AM">11:00 AM</option>
...
</select>
To
<select class="to">
<option value="10:00 AM">10:00 AM</option>
<option value="10:15 AM">10:15 AM</option>
<option value="10:30 AM">10:30 AM</option>
<option value="10:45 AM">10:45 AM</option>
<option value="11:00 AM">11:00 AM</option>
<option value="11:15 AM">11:15 AM</option>
<option value="11:30 AM">11:30 AM</option>
<option value="11:45 AM">11:45 AM</option>
<option value="12:00 PM">12:00 PM</option>
...
</select>

我想防止人们从中选择等于或晚于""的",例如上午11点到9点的以及其他没有意义的组合。

我使用的是Datejs和jQuery。我包含了date.min.js脚本,并得到了以下几乎可以完成任务的代码:

$('.from').on('change', function(e) {
  var from_time = Date.parse($(this).val());
  // Ensure 1 hour difference
  var from_time_adj = new Date();
  from_time_adj.setTime(from_time.getTime() + (60 * 60 * 1000));
  $('.to option').each(function(index, el) {
    var to_time = Date.parse($(el).val());
    if (to_time < from_time_adj) {
      $(el).attr('disabled', true);
    }
  });
});

$('.to').on('change', function(e) {
  var to_time = Date.parse($(this).val());
  // Ensure 1 hour difference
  var to_time_adj = new Date();
  to_time_adj.setTime(to_time.getTime() - (60 * 60 * 1000));
  $('.from option').each(function(index, el) {
    var from_time = Date.parse($(el).val());
    if (from_time > to_time_adj) {
      $(el).attr('disabled', true);
    }
  });
});

以下是"几乎可以工作"的全部内容:JSFiddle

它在某个时刻变得很奇怪,例如:

步骤1:从上午11点开始设置-可以

步骤2:将设置为下午2:00-可以

步骤3:将设置为晚上8:00-哎呀!此时,的已禁用下午1:00后的所有

什么东西?它在2次左右的变化后开始做这种奇怪的事情。进一步尝试使用from/to值显示了这一点。

我意识到我在代码逻辑中有一个错误,但我找不到它。

您也需要启用:

JSFIDDLE

$('.from').on('change', function(e) {
  var from_time = Date.parse($(this).val());
  var from_time_adj = new Date();
  from_time_adj.setTime(from_time.getTime() + (60 * 60 * 1000));
  $('.to option').each(function(index, el) {
    var to_time = Date.parse($(el).val());
    $(el).attr('disabled', to_time < from_time_adj); // disables when statement is true, enables when false
  });
});
$('.to').on('change', function(e) {
  var to_time = Date.parse($(this).val());
  var to_time_adj = new Date();
  to_time_adj.setTime(to_time.getTime() - (60 * 60 * 1000));
  $('.from option').each(function(index, el) {
    var from_time = Date.parse($(el).val());
    $(el).attr('disabled', to_time > to_time_adj); // disables when statement is true, enables when false
  });
});