自动以HTML格式显示正确的时间安排

时间:2018-10-18 04:31:57

标签: javascript jquery html

一个人的周一,周三和周五的办公时间为:上午7:00-下午7:00,周二和周四的办公时间为上午10:00 –晚上9:00。如果所选日期是星期一,星期三或星期五,我希望下拉菜单仅显示7:00 AM-7:00 PM。如果表格上的选定日期是星期二或星期四,则仅显示上午10:00 –晚上9:00的时间。

<form action="/submission.php" method="POST">
    <Label>Date Of Appointment</label>
    <input type="date" name="dateOfAppointment">
    <br><br>
    <Label>Time Of Appointment</label>
    <select name="appointmentTiming">
      <option value="7:00 AM">7:00 AM</option>
      <option value="8:00 AM">8:00 AM</option>
      <option value="9:00 AM">9:00 AM</option>
      <option value="10:00 AM">10:00 AM</option>
      <option value="11:00 AM">11:00 AM</option>
      <option value="12:00 PM">12:00 PM</option>
      <option value="1:00 PM">1:00 PM</option>
      <option value="2:00 PM">2:00 PM</option>
      <option value="3:00 PM">3:00 PM</option>
      <option value="4:00 PM">4:00 PM</option>
      <option value="5:00 PM">5:00 PM</option>
      <option value="6:00 PM">6:00 PM</option>
      <option value="8:00 PM">8:00 PM</option>
      <option value="9:00 PM">9:00 PM</option>
    </select>
    <br><br>
</form>

2 个答案:

答案 0 :(得分:3)

您可以尝试以下代码:

    <form action="/submission.php" method="POST">
        <Label>Date Of Appointment</label>
        <input id="date" type="date" name="dateOfAppointment">
        <br><br>
        <Label>Time Of Appointment</label>
        <select id="hours" name="appointmentTiming">

        </select>
        <br><br>
    </form>
    <script type="text/javascript">
     $(document).ready(function () {
    var now = new Date();
    var today = now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + 
       now.getDate();
       $('#date').val(today);
       changeHours();
     });

    date = document.getElementById('date');
    date.addEventListener('change', changeHours)
function changeHours(){

      var day = new Date( date.value).getDay();

      dropdown = document.getElementById('hours');
      dropdown.innerHTML = '';
      if (day==1 || day==3 || day==5) {
        start = 7;
        hours = 12;
      }
      if (day==2 || day == 4) {
        start = 10;
        hours = 11;
      }

      for(i=0; i<=hours;i++ ){
        time = start + i;
        option = '<option value="'+time+':00 AM">'+time+':00 AM</option>';
        if (time>=12) {
          time= time-12;
          option = '<option value="'+time+':00 PM">'+time+':00 PM</option>';
        }
        dropdown.innerHTML += option;
      }

    }
    </script>

答案 1 :(得分:0)

您可以使用以下JS代码获取所选日期:

var selectedDateEle = document.getElementsByName('dateOfAppointment')[0];
var selectedDay;
selectedDateEle.onchange = function(){
    selectedDay = new Date(selectedDateEle.value).getDay();
}

这将为您提供当天的整数值,其中Sun = 0,Sat = 6。 您可以进一步使用该值来更改下拉菜单。