PHP 下拉框(Dropdown List)是一种常见的 HTML 表单元素,用于让用户从预定义的选项中选择一个值。日期选择下拉框通常用于选择特定的日期,例如年、月、日。
以下是一个简单的 PHP 下拉框选择日期的示例:
<?php
$years = range(1900, date('Y'));
$months = range(1, 12);
$days = range(1, 31);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Date Selector</title>
</head>
<body>
<form action="submit.php" method="post">
<label for="year">Year:</label>
<select name="year" id="year">
<?php foreach ($years as $year): ?>
<option value="<?php echo $year; ?>"><?php echo $year; ?></option>
<?php endforeach; ?>
</select>
<label for="month">Month:</label>
<select name="month" id="month">
<?php foreach ($months as $month): ?>
<option value="<?php echo $month; ?>"><?php echo $month; ?></option>
<?php endforeach; ?>
</select>
<label for="day">Day:</label>
<select name="day" id="day">
<?php foreach ($days as $day): ?>
<option value="<?php echo $day; ?>"><?php echo $day; ?></option>
<?php endforeach; ?>
</select>
<input type="submit" value="Submit">
</form>
</body>
</html>
原因:不同月份的天数不同,例如2月可能有28天或29天,4月、6月、9月、11月只有30天。
解决方法:根据选择的月份动态生成天数。
<?php
$years = range(1900, date('Y'));
$months = range(1, 12);
function getDaysInMonth($year, $month) {
return cal_days_in_month(CAL_GREGORIAN, $month, $year);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Date Selector</title>
</head>
<body>
<form action="submit.php" method="post">
<label for="year">Year:</label>
<select name="year" id="year" onchange="updateDays()">
<?php foreach ($years as $year): ?>
<option value="<?php echo $year; ?>"><?php echo $year; ?></option>
<?php endforeach; ?>
</select>
<label for="month">Month:</label>
<select name="month" id="month" onchange="updateDays()">
<?php foreach ($months as $month): ?>
<option value="<?php echo $month; ?>"><?php echo $month; ?></option>
<?php endforeach; ?>
</select>
<label for="day">Day:</label>
<select name="day" id="day">
<option value="">Select Day</option>
</select>
<input type="submit" value="Submit">
</form>
<script>
function updateDays() {
var year = document.getElementById('year').value;
var month = document.getElementById('month').value;
var daySelect = document.getElementById('day');
daySelect.innerHTML = '<option value="">Select Day</option>';
if (year && month) {
var days = <?php echo json_encode(getDaysInMonth($years[0], $months[0])); ?>;
for (var i = 1; i <= days; i++) {
var option = document.createElement('option');
option.value = i;
option.text = i;
daySelect.add(option);
}
}
}
</script>
</body>
</html>
希望这些信息对你有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云