DatePicker in HTML5 setting current date - javascript

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.

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>

Related

Change date when status is updated

Hi guys I'm looking to write a javascript to change the date in the date box when I update the status select box.
For example the initial date on the datebox is 6/1/2021. And I will click on status rejected. The date should automatically change to today 6/3/21 without manually clicking the date picker box
<html>
<body>
<select>
<option value="Offered">Offered</option>
<option value="Accepted">Accepted</option>
<option value="Rejected">Rejected</option>
</select">
<input type="date" id="date" name="date">
<input type="submit" value="Submit">```
</body>
</html>
Then you have to call the onChange() event on select and remove the if condition-
<html>
<head>
<script>
function myFunction() {
let date = new Date();
let year = date.getFullYear();
let month = (date.getMonth() + 1).toString().length == 1 ? '0' + (date.getMonth() + 1).toString() : (date.getMonth() + 1).toString();
let day = date.getDay().toString().length == 1 ? '0' + date.getDay().toString() : date.getDay().toString();
let showDate = year + '-' + month + '-' + day;
document.getElementById("date").value = showDate;
}
</script>
</head>
<body>
<select id="mySelect" onchange="myFunction();">
<option value="Offered">Tesla</option>
<option value="Accepted">Volvo</option>
<option value="Rejected">Mercedes</option>
</select>
<input type="date" id="date" name="date">
<input type="submit" value="Submit">
</body>
</html>
I hope this answers your question. I have added comments for better clarity. In case you have any issues, let me know.
//Getting the select HTML node.
const select = document.querySelector("#select");
//Getting the date input node.
const date = document.querySelector("#date");
//Adding a change event listener to the select node.
select.addEventListener('change', () => {
//Had to use ISOString with slice method, since the date picker only accepts the date value in "yyyy-MM-dd" format.
date.value = new Date().toISOString().slice(0, 10);
});
<html>
<body>
<select id="select">
<option value="Offered">Offered</option>
<option value="Accepted">Accepted</option>
<option value="Rejected">Rejected</option>
</select>
<input type="date" id="date" name="date">
<input type="submit" value="Submit">
</body>
</html>
This should work. When using type="date" you need to provide a date in this format YYYY-MM-DD (rfc3339).
HTML
<html>
<body>
<select onchange="changeDate()">
<option value="Offered">Tesla</option>
<option value="Accepted">Volvo</option>
<option value="Rejected">Mercedes</option>
</select">
<input type="date" id="date" name="date">
<input type="submit" value="Submit">
</body>
</html>
Javascript
const changeDate = (val) => {
// Format date to your need
const now = new Date();
const day = ("0" + now.getDate()).slice(-2);
const month = ("0" + (now.getMonth() + 1)).slice(-2);
const today = `${now.getFullYear()}-${month}-${day}`;
console.log(`Today is: ${today}`);
// Set date input
let date = document.getElementById('date');
date.value = today;
}

Input type Password not working autocomplete="off" using Angularjs

I have used autocomplete="off" but not working in password input please check below atteched my demo code.
<form name="testfrm" ng-submit="test(testfrm)" autocomplete="off">
<input type="password" id="passwordFiled" name="test" autocomplete="off" required>
<button type="submit" class="btn"> test </button>
</form>
Please let me know how to disabled autocomplete for password filed
You can add a name-changer function for the password field, it can be a possible solution, here's the code I tried:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
// Returns random string based on 32 different characters and 4 dashes ("-")
function string_generator() {
var str = function() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
};
return (str() + str() + "-" + str() + "-" + str() + "-" + str() + "-" + str() + str() + str());
}
$(document).ready(function() {
$("#passwordField").attr("name", string_generator());
});
</script>
</head>
<body>
<form name="testfrm" ng-submit="test(testfrm)">
<input type="password" id="passwordField" name="test" autocomplete="off" required>
<button type="submit" class="btn"> test </button>
</form>
</body>
</html>
Let me know if it works (if it doesn't work, please check the password-field id, because in my code is "passwordField", while in your is "passwordFiled")
Anyway, if you need the original name test as the url variable, this answer is supposed to be useless

Change attribute min of input type=date in javascript

I have two input fields of type date.
<input id="startdate" type="date" min='#DateTime.Now.AddDays(1).ToShortDateString()' onchange="handler(event)" />
<input id="enddate" type="date" min="#DateTime.Now.AddDays(2).ToShortDateString()" onchange="handler(event)" />
I want in enddate min date be alaways two days ahead towards selected date in start date. So far I use script adding days and selecting attribute min.
<script type="text/javascript">
function handler(e) {
var someDate = new Date($("#startdate").val());
document.getElementById("enddate").setAttribute('min', addDays($("#startdate").val(),2));
}
</script>
<script type="text/javascript">
function addDays(date, days) {
var result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}
</script>
This proposition is not working. Any ideas?
using moment.js
<input id="startdate" type="date" min='' />
<input id="enddate" type="date" min="" />
<!-- import moment.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script>
(function(){
$('#startdate').attr('min', moment().format('YYYY-MM-DD'))
$('#startdate').on('change', function(e){
var startDate = $(this).val();
var endDate = moment(startDate).add(2, 'days').format('YYYY-MM-DD');
$('#enddate').attr('min', endDate);
})
})()
</script>

Adding days by 7, when I choose a date?

I just want to ask here about on how to add dates in the "input" statement in the form? When I choose a date, it will increment the days by 7 and display it to the "input" statement the type is date. Here's my code.
just click this link, to view the image.
<html>
<head>
<title>Date Sample</title>
</head>
<body>
<form>
Start Date:<br/>
<input type="date" name="sdate" id="sdate"/>
<br/>
End Date:<br/>
<input type="date" name="edate" id="edate"/>
</form>
</body>
</html>
Attach change listener
Use DateObj.getDate and DateObj.setDate methods to get required Date
Format the DateObj in YYYY-MM-DD to set the value
Note: I have added readonly attribute for end-date so that user can not edit that value.
$('#sdate').change(function() {
if (this.value) {
var d = new Date(this.value);
var newDate = d.setDate(d.getDate() + 7);
var dateObj = new Date(newDate);
var day = ("0" + dateObj.getDate()).slice(-2);
var month = ("0" + (dateObj.getMonth() + 1)).slice(-2);
$('#edate').val(dateObj.getFullYear() + "-" + (month) + "-" + (day));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form>
Start Date:
<br/>
<input type="date" name="sdate" id="sdate" />
<br/>End Date:
<br/>
<input type="date" name="edate" id="edate" readonly />
</form>

Start date End date validation in angularjs submit form should be disabled

I dont wana submit my form if Start date-End date validation fails...In my form if i have this...
<form name="scheduleForm" id="scheduleForm" class="form-vertical" novalidate>
<input type="text" placeholder="Start Date" ng-model="schedule.startDate" class="form-control" ui-date novalidate required>
<input type="text" name="endDate" placeholder="End Date" ng-model="schedule.endDate" class="form-control" ui-date novalidate ng-change='checkErr(schedule.startDate,schedule.endDate)' required>
<button class="btn btn-primary" ng-click="addSchedule(schedule)" ng-disabled="errMessage || scheduleForm.$invalid">Add Schedule</button>
And in the controller :
$scope.checkErr = function(startDate,endDate) {
$scope.errMessage = '';
var curDate = new Date();
if(new Date(startDate) > new Date(endDate)){
$scope.errMessage = 'End Date should be greater than start date';
// var err=function() {
// $window.alert('End Date should be greater than start date');};
// err();
return false;
}
if(new Date(startDate) < curDate){
$scope.errMessage = 'Start date should not be before today.';
// var err=function() {
// $window.alert('Start date should not be before today.');};
// err();
return false;
}
};
and in add function:
$scope.addSchedule=function(schedule){
$scope.schedules.push({
startDate: schedule.startDate,
endDate: schedule.endDate,
});
schedule.startDate='';
schedule.endDate='';
};
prob is button looks disable bt its allowing data to be added... do help thank in advance
to compare time properly should use getTime() function
if(new Date(startDate).getTime() > new Date(endDate).getTime())
and check date validation in button so no need to use checkErr() on end date change
<button class="btn btn-primary" ng-click="addSchedule(schedule)" ng-disabled="checkErr(schedule.startDate,schedule.endDate)|| scheduleForm.$invalid">Add Schedule</button>
and your checkErr function like:
$scope.checkErr = function(startDate,endDate) {
var curDate = new Date();
// can set error message if need to show
if(new Date(startDate).getTime() > new Date(endDate).getTime()){
return true; // if invalid
}
if(new Date(startDate).getTime() < curDate.getTime()){
return true; // if invalid
} else {
return false // if valid
}
};
Why not you add validation when elements are ready. Look at the demo here https://plnkr.co/edit/JunWzLjhLCPMqZnxsSYw?p=preview
var app = angular.module('myApp', ['ui.date']);
app.controller('MainCtrl', function($scope) {
$scope.schedule = {};
$scope.dateOptions = {
changeYear: true,
date:$scope.schedule.startDate,
changeMonth: true,
yearRange: '1900:-0',
maxDate: new Date(new Date().setDate(new Date().getDate() + 2)),
minDate:new Date()
};
$scope.addSchedule=function(schedule){
console.log($scope.schedule)
};
});
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>
<script src="date.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<form name="scheduleForm" id="scheduleForm" class="form-vertical" novalidate>
<input type="text" placeholder="Start Date" ng-model="schedule.startDate" ui-date-format="DD, d MM, yy"
class="form-control" min-date="minDate" max-date="maxDate" ui-date="dateOptions" novalidate required>
<!--<input type="text" name="endDate" placeholder="End Date" ui-date-format="DD, d MM, yy" ng-model="schedule.endDate" class="form-control" ui-date novalidate ng-change='checkErr(schedule.startDate,schedule.endDate)' required>
-->
<button class="btn btn-primary" ng-click="addSchedule(schedule)" ng-disabled="scheduleForm.$invalid">Add Schedule</button>
</form>
</body>
</html>

Categories

Resources