Reputation: 657
I have a problem with my datepicker in HTML5. I want to set the current date with Javascript but I always get how the date should be provided.
Here is my code:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<script>
//Declare variables
var today = new Date();
// Set values
$("#datePicker").val(getFormattedDate(today));
// Get date formatted as YYYY-MM-DD
function getFormattedDate (date) {
return date.getFullYear()
+ "-"
+ ("0" + (date.getMonth() + 1)).slice(-2)
+ "-"
+ ("0" + date.getDate()).slice(-2);
}
</script>
<title>Report</title>
<body>
<h1 align="center">Report für informative Ansichten</h1>
<form action="#" th:action="@{/pdf}" method="post">
<div><input name="datePicker" id="datePicker" type="date" min="1900-01-01" required></div>
<span class="validity"></span>
<input type="submit" value="PDF Ausgabe erzeugen"/>
</form>
</body>
</html>
Maybe someone can tell me what I am doing wrong here?
Thanks in advance.
Upvotes: 0
Views: 70
Reputation: 6540
Your code is fine, however, the script tag is above the the HTML so $("#datePicker")
is null, because the HTML has not been yet created.
Either place the script below your HTML or wait for $(document).ready()
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<title>Report</title>
</head>
<body>
<h1 align="center">Report für informative Ansichten</h1>
<form action="#" th:action="@{/pdf}" method="post">
<div><input name="datePicker" id="datePicker" type="date" min="1900-01-01" required></div>
<span class="validity"></span>
<input type="submit" value="PDF Ausgabe erzeugen"/>
</form>
<script>
//Declare variables
var today = new Date();
// Set values
$("#datePicker").val(getFormattedDate(today));
// Get date formatted as YYYY-MM-DD
function getFormattedDate (date) {
return date.getFullYear()
+ "-"
+ ("0" + (date.getMonth() + 1)).slice(-2)
+ "-"
+ ("0" + date.getDate()).slice(-2);
}
</script>
</body>
</html>
Upvotes: 1