我制作了一个基本的打卡时钟网页和 MySQL 数据库, 唯一的问题是,当人们不小心在一天结束时签到而不是签到,反之亦然,这会留下很多空白。
我需要某种代码,在 10:30 之前将“startfinish”值默认为“开始”,在 14:30 之后默认为“结束”,但仍允许用户在需要时更改选项
注意真正确定从哪里开始以及我是否应该使用 javascript 或 php(php 作为“表单操作”位于单独的文件中)
这是我当前需要更改选项的 html 代码:
<select name="startfinish" id="startend" required>
<option selected="selected" disabled selection>Please select</option>
<option value="Start">Start</option>
<option value="End">End</option>
任何帮助将不胜感激
谢谢,
丹尼尔
最佳答案
如果您不反对 PHP,您可以检查当前时间并将其与您指定的时间进行比较。不过,这必须放在您正在处理的文件中,而不是您的操作文件中。
<?php
// Set the default timezone so you don't run into timezone issues
// You can set this to whatever suits your application best
// Full list of supported timezones here: http://php.net/manual/en/timezones.php
date_default_timezone_set('America/Vancouver');
// Compare the current time to the start and end times
// This reads: if current time is before start time, option is selected, otherwise it's not
$start = (strtotime('now') < strtotime('10:30 AM today') ? 'selected="selected"' : '');
// This reads: if current time is after end time, option is selected, otherwise it's not
$end = (strtotime('now') > strtotime(' 2:30 PM today') ? 'selected="selected"' : '');
?>
要在您的选择控件中使用它,您需要在选项中回显变量(为简洁起见以简写形式显示)。如果日期计算正确,该选项将被选中,否则它将保持不变。我从占位符中删除了选择,因为此设置将确保始终选择“开始”或“结束”。
<select name="startfinish" id="startend" required>
<option disabled selection>Please select</option>
<option <?=$start?> value="Start">Start</option>
<option <?=$end?> value="End">End</option>
</select>
在这种情况下使用 PHP 的好处是它在服务器端而不是客户端运行,因此您不必担心用户禁用 Javascript 并破坏您的表单设计。不过,如果您已经在应用程序中依赖 jQuery,那可能不是问题。
关于javascript - 将 html <select> 选项设置为基于当前时间的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30723315/