You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在<input type="date">选中特定日期时禁用对应已占用的<option>时段

实现日期选中后动态禁用已占用时段的方案

步骤1:修正前端基础代码

先把你原代码里的PHP输出语法错误修正,确保时段选项能正常渲染:

<label for="date">Date:</label>
<input type="date" name="date" id="date" min="<?php echo date("Y-m-d"); ?>" required><br>
<label for="time">Choose an appointment time: </label><br>
<select name="time" id="time">
<?php
$sql2 = "SELECT * FROM time";
$result2 = $conn->query($sql2);

while($rows2=$result2->fetch_assoc()) {
    echo '<option value="'.$rows2['time'].'">'.$rows2['time'].'</option>';
}
?>
</select>

步骤2:添加JavaScript动态处理逻辑

给日期输入框绑定change事件,每次选中新日期时,请求后端获取该日期已占用的时段,再对应禁用下拉框里的选项:

document.getElementById('date').addEventListener('change', function() {
    const selectedDate = this.value;
    const timeSelect = document.getElementById('time');
    
    // 先恢复所有时段为可用状态,避免残留之前的禁用设置
    Array.from(timeSelect.options).forEach(option => {
        option.disabled = false;
    });

    if (!selectedDate) return;

    // 发送请求到后端获取已占用时段
    fetch(`get_occupied_times.php?date=${selectedDate}`)
        .then(response => response.json())
        .then(occupiedTimes => {
            // 匹配已占用时段并禁用对应选项
            Array.from(timeSelect.options).forEach(option => {
                if (occupiedTimes.includes(option.value)) {
                    option.disabled = true;
                }
            });
        })
        .catch(error => console.error('获取已占用时段失败:', error));
});

步骤3:编写后端接口get_occupied_times.php

这个文件负责接收日期参数,查询数据库中该日期已被预约的时段,返回JSON格式结果(假设你有存储预约记录的appointments表,包含appointment_date和appointment_time字段):

<?php
// 复用你原代码中的数据库连接
$conn = new mysqli('localhost', '你的用户名', '你的密码', '你的数据库名');

if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}

$selectedDate = $_GET['date'];
$occupiedTimes = [];

// 使用预处理语句防止SQL注入
$sql = "SELECT appointment_time FROM appointments WHERE appointment_date = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $selectedDate);
$stmt->execute();
$result = $stmt->get_result();

while ($row = $result->fetch_assoc()) {
    $occupiedTimes[] = $row['appointment_time'];
}

// 返回JSON格式数据
header('Content-Type: application/json');
echo json_encode($occupiedTimes);

$stmt->close();
$conn->close();
?>

关键注意事项

  • 确保appointments表的日期字段类型为DATE,时段字段和time表的time字段格式完全一致,否则无法匹配
  • 每次切换日期时先恢复所有选项可用,避免之前的禁用状态干扰新日期的时段选择
  • 后端必须用预处理语句,防止SQL注入风险

内容的提问来源于stack exchange,提问作者Kenneth John Correo Ribay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 10:54:18