here is my code,i want to print date in text box after enter date text using onload event.
<!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>
You have to
Date
object (you're missing new
) 2012/12/30
) Change
document.getElementById("fname").value = Date();
to
var now = new Date();
var formatedDate = now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate();
document.getElementById("fname").value = formatedDate;
Note that some browsers accept other formats, but Chrome doesn't, as it complies to the norm .
The value attribute of the input box is a string, but your function is trying to assign a Date object. You need to convert it to a string first. Here's some code that will do it:
<!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>
Try this:
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;
}
Date control in HTML5 accepts in the format of Year - month - day while the new Date()
in JavaScript returns date like eg: Sun Dec 30 2012 10:09:05 GMT+0230
See demo
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.