给定一个输入元素:
<input type="date" />
有没有办法将日期字段的默认值设置为今天的日期?
给定一个输入元素:
<input type="date" />
有没有办法将日期字段的默认值设置为今天的日期?
当前回答
这在一行JS中是可能的。
HTML:
<input type="date" id="theDate">
JS:
document.getElementById('theDate').value = new Date().toISOString().substring(0, 10);
. getelementbyid(“theDate”)。value = new Date(). toisostring()。substring (0, 10); <input type="date" id="theDate">
其他回答
非常简单,只需使用服务器端语言,如PHP,ASP,JAVA,甚至你可以使用javascript。
这是解决方案
<?php
$timezone = "Asia/Colombo";
date_default_timezone_set($timezone);
$today = date("Y-m-d");
?>
<html>
<body>
<input type="date" value="<?php echo $today; ?>">
</body>
</html>
使用input:date元素的. defaultvalue属性将日期的默认值设置为今天的日期。
<input type="date" id="date"/>
window.onload = function loadDate() {
let date = new Date(),
day = date.getDate(),
month = date.getMonth() + 1,
year = date.getFullYear();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
const todayDate = `${year}-${month}-${day}`;
document.getElementById("date").defaultValue = todayDate;
};
loadDate();
或者在窗口加载上使它成为IIFE/self-called函数
window.onload = (function loadDate() {
let date = new Date(),
day = date.getDate(),
month = date.getMonth() + 1,
year = date.getFullYear();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
const todayDate = `${year}-${month}-${day}`;
document.getElementById("date").defaultValue = todayDate;
})();
与使用value属性设置日期不同,使用defaultValue属性提供了动态优势。
另外,注意日期格式必须匹配,因此我使用todayDate的格式为:
年-月-日
我相信这回答了你的问题,除了你想设置一个静态的开始和结束日期。要做到这一点,请遵循以下Mozilla的示例:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date >
这在一行JS中是可能的。
HTML:
<input type="date" id="theDate">
JS:
document.getElementById('theDate').value = new Date().toISOString().substring(0, 10);
. getelementbyid(“theDate”)。value = new Date(). toisostring()。substring (0, 10); <input type="date" id="theDate">
如果你需要填写输入日期时间,你可以使用这个:
<input type="datetime-local" name="datetime"
value="<?php echo date('Y-m-d').'T'.date('H:i'); ?>" />
我也有同样的问题,我用简单的JS解决了它。输入:
<input type="date" name="dateOrder" id="dateOrder" required="required">
JS的
<script language="javascript">
document.getElementById('dateOrder').value = "<?php echo date("Y-m-d"); ?>";
</script>
重点:JS脚本应该在最后一行代码,或者在输入之后,因为如果你把这个代码放在前面,脚本就找不到你的输入。