如何为HTML的input date类型设置默认值为当日日期
解决日期输入框自动填充当日日期的问题
问题根源
- HTML的
value属性无法直接调用JavaScript函数,写value="getDate()"只会把字符串"getDate()"赋值给输入框,不会执行函数。 toDateInputValue()不是JavaScript Date对象的原生方法,调用会直接报错。type="date"的input元素要求value必须是yyyy-MM-dd格式,浏览器会根据系统区域设置自动转换为对应显示格式(比如你需要的dd/mm/yyyy),不需要手动处理显示逻辑。
修正后的完整代码
<!DOCTYPE html> <html> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <body> <form action="" method="post"> {% csrf_token %} <label for="from_date">From Date:</label> <input type="date" id="from_date" name="from_date"> <label for="to_date">To Date:</label> <input type="date" id="to_date" name="to_date"> <input type="submit">  <input type="checkbox" name="new_records" value="new_records" checked> <label for="new_records"> New Records</label>  <input type="checkbox" name="error_records" value="error_records" checked> <label for="error_records"> Error Records</label><br><br> <label for="field">Choose your required field:</label> <select name="field" id="field"> <option value="">--Please choose an option--</option> <option value="started">Started</option> <option value="completed">Completed</option> </select> </form> <script> // 格式化日期为type="date"要求的yyyy-MM-dd格式 function formatDateForInput(date) { const year = date.getFullYear(); // 月份和日期补零,确保是两位数字 const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); return `${year}-${month}-${day}`; } // 页面加载完成后填充当日日期 window.addEventListener('DOMContentLoaded', function() { const today = new Date(); document.getElementById('from_date').value = formatDateForInput(today); document.getElementById('to_date').value = formatDateForInput(today); }); </script> </body> </html>
关键修改说明
- 移除了input元素
value属性中的无效函数调用字符串,改为通过JS动态赋值。 - 新增
formatDateForInput函数,处理日期格式转换,满足原生日期输入框的格式要求。 - 使用
DOMContentLoaded事件确保页面元素加载完成后再执行赋值操作,避免找不到元素的错误。 - 同时为
from_date和to_date两个输入框填充当日日期。
补充提示
- 原生
type="date"输入框会根据用户系统的区域设置自动调整显示格式,只要value是标准的yyyy-MM-dd,浏览器会自动显示为dd/mm/yyyy(如果系统区域是日/月/年格式)。 - 如果需要完全自定义显示格式且放弃原生日期选择器,可以将input的
type改为text,但需要自行实现日期选择逻辑。
内容的提问来源于stack exchange,提问作者Ajay
相关产品推荐
相关产品推荐

