Reputation: 111
I want to display today's date on the input text. But why am I receiving the error after I run on the browser? Is there anything wrong with the code.
HTML
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type=text/javascript>
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd = '0'+dd
}
if(mm<10) {
mm = '0'+mm}
today= mm + '/' + dd + '/' + yyyy;
document.getElementById("today1").value=today;
</script>
<body>
<input id="today1" value="">
</body>
</html>
Upvotes: 0
Views: 1221
Reputation: 68933
Your code is running before the DOM is ready. Wrap your code with DOMContentLoaded. This will ensure that the code will be executed after all the initial HTML has been completely loaded and parsed.
document.addEventListener("DOMContentLoaded", function(event) {
// your code here
});
Working Code Example:
<script type=text/javascript>
document.addEventListener("DOMContentLoaded", function(event) {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd = '0'+dd
}
if(mm<10) {
mm = '0'+mm}
today= mm + '/' + dd + '/' + yyyy;
document.getElementById("today1").value=today;
});
</script>
<input id="today1" value="">
Upvotes: 1
Reputation: 2709
Run your javaScript only after the DOM is loaded.
document.addEventListener("DOMContentLoaded", function(event) {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd = '0'+dd
}
if(mm<10) {
mm = '0'+mm}
today= mm + '/' + dd + '/' + yyyy;
document.getElementById("today1").value=today;
});
Upvotes: 1