[英]how to print date in input text box in html
这是我的代码,我想在使用onload事件输入日期文本后在文本框中打印日期。
<!DOCTYPE html>
<html>
<head>
<script>
function displayDate() {
document.getElementById("fname").value = Date();
}
</script>
</head>
<body onload="displayDate()">
Enter date: <input type="date" id="fname" readonly />
</body>
</html>
你必须
Date
对象(你错过了new
) 2012/12/30
) 更改
document.getElementById("fname").value = Date();
至
var now = new Date();
var formatedDate = now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate();
document.getElementById("fname").value = formatedDate;
请注意,某些浏览器接受其他格式,但Chrome不接受其他格式,因为它符合规范 。
输入框的value属性是一个字符串,但您的函数正在尝试分配Date对象。 您需要先将其转换为字符串。 这里有一些代码可以做到:
<!DOCTYPE html>
<html>
<head>
<script>
function displayDate() {
var today=new Date();
var date=today.toISOString().slice(0, -14);
// Strip last 14 characters, ISO format is like
// 2012-12-30T17:41:49.027Z but we want
// 2012-12-30
document.getElementById("fname").value=date;
}
</script>
</head>
<body onload="displayDate()">
Enter date: <input type="date" id="fname" readonly>
</body>
</html>
尝试这个:
function displayDate() {
var now = new Date();
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = now.getFullYear() + "-" + (month) + "-" + (day);
document.getElementById("fname").value = today;
}
HTML5中的日期控件接受格式为Year - month - day,而JavaScript中的new Date()
返回日期,例如: Sun Dec 30 2012 10:09:05 GMT + 0230
见演示
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.