如何实现复选框选中时填充当前日期至date输入框并入库?
实现「至今」复选框填充当前日期并保存到数据库
一、前端交互实现
给复选框和日期输入框添加id,通过JavaScript监听复选框切换事件,自动完成日期填充或清空:
<div class="form-group"> <label for="recipient-name" class="col-form-label">工作结束日期</label> <input type="date" class="form-control" name="f_tahunakhir" id="f_tahunakhir" value="<?= set_value('f_tahunakhir');?>" autocomplete="off"> <input type="checkbox" class="ui-datepicker-current" name="current_date" id="current_date"> 至今 </div> <script> // 获取页面元素 const currentCheckbox = document.getElementById('current_date'); const endDateInput = document.getElementById('f_tahunakhir'); // 监听复选框切换事件 currentCheckbox.addEventListener('change', function() { if (this.checked) { // 格式化当前日期为date输入框要求的YYYY-MM-DD格式 const today = new Date(); const formattedDate = `${today.getFullYear()}-${String(today.getMonth()+1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`; // 填充日期并禁用输入框(可选,防止手动修改) endDateInput.value = formattedDate; endDateInput.disabled = true; } else { // 取消勾选时清空日期并启用输入框 endDateInput.value = ''; endDateInput.disabled = false; } }); // 页面加载时,若表单有旧数据,同步复选框和输入框状态 <?php if(set_value('current_date')): ?> currentCheckbox.checked = true; const today = new Date(); const formattedDate = `${today.getFullYear()}-${String(today.getMonth()+1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`; endDateInput.value = formattedDate; endDateInput.disabled = true; <?php endif; ?> </script>
二、后端保存处理(以CodeIgniter框架为例)
接收表单提交的数据,可选强制校验日期避免前端篡改,再写入数据库:
public function save_work_record() { // 获取表单提交的参数 $submitData = [ 'f_tahunakhir' => $this->input->post('f_tahunakhir'), // 记录是否为当前在职状态(可选,方便后续查询) 'is_current' => $this->input->post('current_date') ? 1 : 0 ]; // 若勾选了「至今」,强制设置日期为当前系统日期,提升数据安全性 if ($submitData['is_current']) { $submitData['f_tahunakhir'] = date('Y-m-d'); } // 插入或更新到数据库(假设表名为work_records) $this->db->insert('work_records', $submitData); // 操作完成后跳转或提示 redirect('work_records'); }
注意事项
- 前端禁用输入框是优化用户体验,避免勾选「至今」后还能手动修改日期;如果需要允许修改,去掉
endDateInput.disabled = true即可 - 后端强制设置日期是为了防止前端传递恶意数据,确保数据准确性
- 若为编辑页面,需从数据库读取
is_current状态,初始化复选框和输入框的状态
内容的提问来源于stack exchange,提问作者labkes
相关产品推荐
相关产品推荐

