如何使用Javascript在下拉列表中显示时间表?

时间:2019-06-18 04:51:54

标签: javascript jquery time

我想显示一个30分钟间隔的时间表列表,该列表基于日期。如果日期是今天和过去的时间,那么过去的时间将被禁用。如果该日期不是今天,那么它将显示所有时间表。

 let $select = jQuery("#s_time");
    
        for (let hr = 8; hr < 22; hr++) {
    
        let hrStr = hr.toString().padStart(2, "0") + ":";
    
        let val = hrStr + "00";
        $select.append('<option val="' + val + '">' + val + '</option>');
    
        val = hrStr + "30";
        $select.append('<option val="' + val + '">' + val + '</option>')
    
        }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
     <select name="s_time" id="s_time" class="form-control bmg-hrs-mins-input">
     </select>
    </div>

如果日期是今天,如果不是今天,我希望过去的时间将被禁用,那么它将显示所有时间表。

2 个答案:

答案 0 :(得分:2)

您可以有条件地disable选项。请尝试以下操作:

let $select = $("#s_time");
for (let hr = 8; hr < 22; hr++) {

  let hrStr = hr.toString().padStart(2, "0") + ":";

  let val = hrStr + "00";

  $select.append('<option val="' + val + '" ' + (new Date().getHours() >= hr ? 'disabled="disabled"' : '') + '>' + val + '</option>');

  val = hrStr + "30";
  $select.append('<option val="' + val + '" ' + (new Date().getHours() > hr || (new Date().getHours() >= hr && new Date().getMinutes() > 30) ? 'disabled="disabled"' : '') + '>' + val + '</option>')

}
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
<div>
  <select name="s_time" id="s_time" class="form-control bmg-hrs-mins-input"></select>
</div>

答案 1 :(得分:2)

首先,我们需要将给定日期与今天的日期进行比较。

JavaScript代码

var GivenDate = '2019-06-20';
var CurrentDate = new Date();
GivenDate = new Date(GivenDate);

if(GivenDate > CurrentDate){
   // enable select field 
     $('#s_time').prop('disabled', false);
}else{
   // disable select field 
    $('#s_time').prop('disabled', true);
}

我希望这会有所帮助! :)