HTML - How do I add days to an input date using javascript? - javascript

I'm trying to make an alert to user when choose a date. For example, when user choose 2018-09-13, then the alert will show message "7 days later will be 2018-09-20". But instead, the alert message shows 2018-09-137.
<input type="date" name = "date" id = "date" onchange="javascript:var chooseDate=(this.value)+7; alert('7 days later will be '+chooseDate);" >
How should I add days into the date ?? please help, thank you.

this.value will return the date as string using the format YYYY-MM-DD, so if you "add" 7, it will be YYYY-MM-DD7. What you could do is create a new Date object, and then add the days you want, like this:
var chooseDate=new Date(this.value);
chooseDate.setDate(chooseDate.getDate()+7);
alert('7 days later will be '+chooseDate);
This will give you the complete date, though, which is something you probably don't want, so you would have to get the values you actually need, like this:
var chooseDate=new Date(this.value);
chooseDate.setDate(chooseDate.getUTCDate()+7);
var futureDate = chooseDate.getFullYear()+'-'+('0'+(chooseDate.getMonth()+1)).slice(-2)+'-'+('0'+(chooseDate.getDate())).slice(-2);
alert('7 days later will be '+chooseDate);
Here you have a working example:
<input type="date" name = "date" id = "date" onchange="var chooseDate=new Date(this.value);chooseDate.setDate(chooseDate.getUTCDate()+7);var futureDate=chooseDate.getFullYear()+'-'+('0'+(chooseDate.getMonth()+1)).slice(-2)+'-'+('0'+(chooseDate.getDate())).slice(-2);alert('7 days later will be '+futureDate);" >

How about this in :
addDays = function(input_date, days) {
var date = new Date(input_date);
date.setDate(date.getDate() + days);
return date;
}
You then call do addDays(this.value, 7) in onchange().
And, please reference on getDate() and setDate().

You are working with string instead of a date object:
function lPad(val) {
return ((10 > val ? '0' : '') + val);
}
function add(input, unit, value) {
var cur = input.value;
var byValue = Number(value);
if (!/^\d{4}\-\d{2}\-\d{2}$/.test(cur) || !/day|month|year/.test(unit) || isNaN(byValue)) {
console.warn('invalid parameters!');
return false;
}
var dt = new Date(cur.replace(/\-/g, '/'));
if (!dt || isNaN(dt)) {
console.warn('invalid date!');
return false;
}
if ('day' === unit) {
dt.setDate(dt.getDate() + byValue);
} else if ('month' === unit) {
dt.setMonth(dt.getMonth() + byValue);
} else {
dt.setFullYear(dt.getFullYear() + byValue);
}
input.value = [dt.getFullYear(), lPad(1 + dt.getMonth()), lPad(dt.getDate())].join('-');
console.log(cur, value, unit, '=', input.value);
return true;
}
<input type="date" onchange="add(this,'day','+7');" title="+7 days" />
<input type="date" onchange="add(this,'month','-1');" title="-1 month" />
<input type="date" onchange="add(this,'year','+2');" title="+2 year" />

try this one ...
<input type="date" name = "date" id = "date" onchange="ggrr(this)" >
<script>
function ggrr(input){
var dateString = input.value;
var myDate = new Date(dateString);
var d = new Date(Date.parse(myDate));
var y = d.getFullYear();
var da = d.getDate() + 7;
var m = d.getMonth();
console.log(y+':'+m+':'+da);
}
</script>

Related

How to validate date in Javascript?

I have a textbox which allows users to choose a date from a calendar in mm/dd/yyyy format. I used the pikaday and moment libraries to achieve this. Now, if the user selects a date that is not in the future, I want to show an error in a label saying that the date is invalid. What is the 'best' way to achieve this? Working with dates in Javascript turned out to be quite a headache.I have provided my current approach:
textbox:
<asp:TextBox ID="txtDepartureDate" runat="server" ForeColor="Gray" onfocus="txtOnFocusDeparture(this)" onblur="txtOnBlurDeparture(this)" oninput="oninputDeparture()" AutoPostBack="True">DEPARTURE DATE</asp:TextBox>
script:
<script type="text/javascript">
function oninputDeparture() {
var inputDate = moment(document.getElementById('txtDepartureDate').value, 'DD/MM/YYYY');
var todayDate = moment().format('DD/MM/YYYY');
var lblError = document.getElementById('lblError');
var daysDiff = todayDate.diff(inputDate, 'days');
if (daysDiff <= 0) {
lblError.innerText = "Departure Day should be after today";
}
else {
lblError.innerText = "";
}
}
</script>
var todayDate = moment().format('DD/MM/YYYY');
var lblError = document.getElementById('lblError');
var daysDiff = todayDate.diff(inputDate, 'days');
moment.diff requires a moment object. todayDate is assigned as string in this case.
Also consider quick exit when the user is still typing
Have a look at the example.
var dateInput = document.getElementById('txtDepartureDate');
var lblError = document.getElementById('lblError');
function setError(text) {
lblError.innerText = text
}
function oninputDeparture() {
var value = dateInput.value;
var dateValue = moment(value, 'DD/MM/YYYY');
if (value.length < 10 || !dateValue.isValid()) {
return;
}
var todayDate = moment();
var daysDiff = todayDate.diff(dateValue, 'days');
if (daysDiff >= 0 && !dateValue.isAfter(todayDate, 'days')) {
setError("Departure Day should be after today");
} else {
setError("");
}
}
setTimeout(() => {
dateInput.value = moment().add(1, 'days').format('DD/MM/YYYY')
oninputDeparture()
}, 1000)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>
<input id="txtDepartureDate" type="text" oninput="oninputDeparture()" />
<div id="lblError"></div>

How do I reference the index of an array without knowing what it is in Javascript?

I'm making a calendar app where I'm trying to validate if the date entered is during the current semester, and then see if it is a holiday that we don't have class. I have an index of all of the dates that we are out with the names of the respective holidays, but when I tried to use indexOf, the code broke.
this is the html:
<form onsubmit="holiday()" method="post">
<fieldset>
Enter Date: <input type='date' id="dat"><p>
<input class="ubmit" type=submit >
</fieldset>
</form>
<p id="output"></p>
this is the js:
var dvalue = document.getElementById("dat").value;
function holiday(){
var txt ="boo";
dvalue=Date.parse(dvalue);
console.log(dvalue);
if (dvalue<1473033600000 || dvalue>1494979200000 || dvalue=="NaN"){
txt="This is not a valid date for this calendar app";
}
else function validate(dvalue){
var holidayz=new Array();
holidayz[0]=["Columbus Day",1473033600000];
holidayz[1]=["Fall Recess",1476057600000];
holidayz[2]=["Thanksgiving Recess",1479859200000];
holidayz[3]=["Thanksgiving Recess",1479945600000];
holidayz[4]=["Thanksgiving Recess",1480032000000];
holidayz[5]=["Thanksgiving Recess",1480118400000];
holidayz[6]=["President's Day",1487548800000];
holidayz[7]=["Spring Recess",1489363200000];
holidayz[8]=["Spring Recess",1489449600000];
holidayz[9]=["Spring Recess",1458000000000];
holidayz[10]=["Spring Recess",1489622400000];
holidayz[11]=["Spring Recess",1489708800000];
holidayz[12]=["Reading Day",1494288000000];
holidayz[13]=["Memorial Day",1496016000000];
holidayz[14]=["Independence Day",1499126400000];
if (holidayz.includes(dvalue)){
var mydate = new Date(dvalue);
console.log("<p>" + mydate + "<p>");
var day = mydate.getUTCDate();
var month = mydate.getMonth()+1;
var year = mydate.getFullYear();
console.log (month + "/" + day +"/" + year);
var holival= asList(holidayz).indexOf(dvalue);
console.log(holival)
}
}
console.log(txt)
document.getElementById("output").innerHTML = txt;
}
Try this,
var dvalue = document.getElementById("dat").value;
function holiday(){
var txt ="boo";
dvalue=Date.parse(dvalue);
console.log(dvalue);
if (dvalue<1473033600000 || dvalue>1494979200000 || dvalue=="NaN"){
txt="This is not a valid date for this calendar app";
} else {
var holidayz=new Array();
holidayz[0]=["Columbus Day",1473033600000];
holidayz[1]=["Fall Recess",1476057600000];
holidayz[2]=["Thanksgiving Recess",1479859200000];
holidayz[3]=["Thanksgiving Recess",1479945600000];
holidayz[4]=["Thanksgiving Recess",1480032000000];
holidayz[5]=["Thanksgiving Recess",1480118400000];
holidayz[6]=["President's Day",1487548800000];
holidayz[7]=["Spring Recess",1489363200000];
holidayz[8]=["Spring Recess",1489449600000];
holidayz[9]=["Spring Recess",1458000000000];
holidayz[10]=["Spring Recess",1489622400000];
holidayz[11]=["Spring Recess",1489708800000];
holidayz[12]=["Reading Day",1494288000000];
holidayz[13]=["Memorial Day",1496016000000];
holidayz[14]=["Independence Day",1499126400000];
holidayz[15]=["Test Day",1476921600000];
for(var i=0; i<holidayz.length; i++){
if ((holidayz[i][1])==dvalue){
var mydate = new Date(dvalue);
console.log("<p>" + mydate + "<p>");
var day = mydate.getUTCDate();
var month = mydate.getMonth()+1;
var year = mydate.getFullYear();
console.log (month + "/" + day +"/" + year);
var holival= i; //asList(holidayz).indexOf(dvalue);
console.log(holival);
break;
}
}
}
console.log(txt);
}

How to load datetimepicker with different date-range for multiple inputs

I want new date range in each box, but it return only last text-box date range. I also made text boxes id's dynamic but still I am facing this issues. I have start date and end date for each text box and I calculated date range in PHP for start date and end date and disabled all those dates which is selected by user in their start date and date all is working fine but it returns last textbox dates disabled in datepicker.
Here is the screenshot-
Sample Image
Javascript function for datepicker to disbaled dates for each box -
$(function () {
var count = $('#count').val();
var uid = $('#usersId').val();
var pid = $('#projectsId').val();
for (i = 1; i <= count; i++) {
$('#projectAssStartDate' + i).datepicker({
beforeShowDay: function (date) {
var dateString = jQuery.datepicker.formatDate('yy-mm-dd', date);
minDate: 0;
alert(dateRange);
console.log(dateString);
return [dateRange.indexOf(dateString) == -1];
}
});
var date_range = $('#calendarDateString' + i).val();
var newdate = date_range.replace(/,(?=[^,]*$)/, '');
var res = '"' + newdate + '"';
var startDate, endDate, dateRange = res;
$('#projectAssEndDate' + i).datepicker({
beforeShowDay: function (date) {
var dateString = jQuery.datepicker.formatDate('yy-mm-dd', date);
console.log(dateString);
return [dateRange.indexOf(dateString) == -1];
}
});
}
});
HTML for create boxes id's dynamic and fetch values from it.
<input type="text" class='datepicker' size='11' title='D-MMM-YYYY' name="projectAssStartDate[]" id="projectAssStartDate<?php echo $id;?>" value="" style="padding: 7px 8px 7px 8px;font-weight: bold;" />
<input type="text" class='datepicker' size='11' title='D-MMM-YYYY' name="projectAssEndDate[]" id="projectAssEndDate<?php echo $id;?>" value="" style="padding: 7px 8px 7px 8px;font-weight: bold;" />
<input id="calendarDateString<?php echo $id;?>" name="calendarDateString<?php echo $id;?>" title='D-MMM-YYYY' type="text" value="<?php echo $string;?>" />
<input id="projectsId" name="projectsId[]" type="hidden" value="<?php echo $rows['PROJECT_ID'];?>" />
<input id="usersId" name="usersId[]" type="hidden" value="<?php echo $rows['UM_ID'];?>" />
Please check the answer and reply whether this is the way you needed it to go. If not please comment what change you want with respect to this below code result. And I'm sorry that I have manipulated few of your values to ease my result. Will give details explanation if this is what you are expecting.
$(function () {
var count = 2;//$('#count').val();
var uid = $('#usersId').val();
var pid = $('#projectsId').val();
// populate the array
var startDatearray= ["index 0","2016-06-15","2016-06-20"]; // you dont need to create this array .. just fetch these dates from your database as u need
var endDatearray=["index 0","2016-06-21","2016-06-25"];
var i;
for (i = 1; i <= count; i++) {
$('#projectAssStartDate' + i).datepicker({
beforeShowDay: function (date) {
var i=parseInt($(this).attr('id').replace(/[^0-9\.]/g, ''), 10); // as i wont get here so i took it from the current id
var startDate = startDatearray[i], // some start date
endDate = endDatearray[i]; // some end date
var dateRange = [];
for (var d = new Date(startDate); d <= new Date(endDate); d.setDate(d.getDate() + 1)) {
dateRange.push($.datepicker.formatDate('yy-mm-dd', d));
}
var dateString = jQuery.datepicker.formatDate('yy-mm-dd', date);
minDate: 0;
//alert(date);
console.log(dateString +"__"+[dateRange.indexOf(dateString) == -1] +"__"+dateRange);
return [dateRange.indexOf(dateString) != -1]; // if u need the opposit then you can use { == -1}
}
});
var date_range = $('#calendarDateString' + i).val();
var newdate = date_range.replace(/,(?=[^,]*$)/, '');
var res = '"' + newdate + '"';
var startDate, endDate, dateRange = res;
$('#projectAssEndDate' + i).datepicker({
beforeShowDay: function (date) {
var dateString = jQuery.datepicker.formatDate('yy-mm-dd', date);
console.log(dateString);
var i=parseInt($(this).attr('id').replace(/[^0-9\.]/g, ''), 10); // as i wont get here so i took it from the current id
var startDate = startDatearray[i], // some start date
endDate = endDatearray[i]; // some end date
var dateRange = [];
for (var d = new Date(startDate); d <= new Date(endDate); d.setDate(d.getDate() + 1)) {
dateRange.push($.datepicker.formatDate('yy-mm-dd', d));
}
var dateString = jQuery.datepicker.formatDate('yy-mm-dd', date);
minDate: 0;
//alert(date);
console.log(dateString +"__"+[dateRange.indexOf(dateString) == -1] +"__"+dateRange);
return [dateRange.indexOf(dateString) != -1]; // if u need the opposit then you can use { == -1}
}
});
}
});

Validate a condition in HTML form using javascript

I want to create an HTML page with small form.
It Contain
Name
Gender
Date of Birth
I Agree checkbox
Submit button
There should be a condition.
If the age is between 20 & 25 [Calculated based on DOB] the "I Agree" Checkbox should be activated or else it should be deactivated.
Deactivation means, I agree box should not accept any check input.
function myAgeValidation() {
var lre = /^\s*/;
var datemsg = "";
var inputDate = document.as400samplecode.myDate.value;
inputDate = inputDate.replace(lre, "");
document.as400samplecode.myDate.value = inputDate;
datemsg = isValidDate(inputDate);
if (datemsg != "") {
alert(datemsg);
return;
}
else {
//Now find the Age based on the Birth Date
getAge(new Date(inputDate));
}
}
function getAge(birth) {
var today = new Date();
var nowyear = today.getFullYear();
var nowmonth = today.getMonth();
var nowday = today.getDate();
var birthyear = birth.getFullYear();
var birthmonth = birth.getMonth();
var birthday = birth.getDate();
var age = nowyear - birthyear;
var age_month = nowmonth - birthmonth;
var age_day = nowday - birthday;
if(age_month < 0 || (age_month == 0 && age_day <0)) {
age = parseInt(age) -1;
}
//alert(age);
if ((age <= 25 ) && ( age >= 20)) {
document.as400samplecode.agree.disabled=false;
}
else {
alert("age limit is 20 - 25");
}
}
function isValidDate(dateStr) {
var msg = "";
var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;
var matchArray = dateStr.match(datePat); // is the format ok?
if (matchArray == null) {
msg = "Date is not in a valid format.";
return msg;
}
month = matchArray[1]; // parse date into variables
day = matchArray[3];
year = matchArray[4];
if (month < 1 || month > 12) { // check month range
msg = "Month must be between 1 and 12.";
return msg;
}
if (day < 1 || day > 31) {
msg = "Day must be between 1 and 31.";
return msg;
}
if ((month==4 || month==6 || month==9 || month==11) && day==31) {
msg = "Month "+month+" doesn't have 31 days!";
return msg;
}
if (month == 2) { // check for february 29th
var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
if (day>29 || (day==29 && !isleap)) {
msg = "February " + year + " doesn't have " + day + " days!";
return msg;
}
}
if (day.charAt(0) == '0') day= day.charAt(1);
//Incase you need the value in CCYYMMDD format in your server program
//msg = (parseInt(year,10) * 10000) + (parseInt(month,10) * 100) + parseInt(day,10);
return msg; // date is valid
}
<html>
<head>
</head>
<body>
<form name="as400samplecode">
Name: <input type="text" name="namee" required><br>
<br>
gender: <input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female<br>
<br>
<input type="text" name="myDate" size=10 maxlength=10> (in MM/DD/YYYY format)<br>
<br>
<br>
<br>
<input type = "checkbox" name="agree" disabled >I, Agree<br>
<br>
<br>
<input type="button" value="Submit" onclick="Javascript:myAgeValidation()" >
</form>
</body>
</html>
One solution would be to add an "oninput" event to the myDate input element that executes the myAgeValidation function each time the input element's value is changed.
<input type="text" name="myDate" size=10 maxlength=10 oninput="myAgeValidation()">(in MM/DD/YYYY format)
If the element's value it is a valid date, the next step is to check the age range. If the value is within the 20 - 25 range, you can enable the checkbox. Just make sure you set your checkbox back to disabled in case someone enters an acceptable 20-25 age, and then changes it back to something else.
See example solution here:
https://jsfiddle.net/z6hnu7qn/
Optional: I added green, pink, and red css borders to the input field depending on the dates acceptability.
I would also recommend looking at other ways to validate your date string. Just returning an empty string if it's valid and checking if datemsg is an empty string to proceed could lead to problems down the line.
Here is a question addressing date validation in javascript:
How to validate date with format "mm/dd/yyyy" in JavaScript?
There are also a number of popular libraries, like angularjs, that do date validation.

Logic to use to find out if the entered date is today or later

I have function that loops every 500ms, and collects date information:
var mlptoday = {};
var timer = setTimeout(today,500);
function today(){
var d = new Date()
mlptoday.date = checkTime(d.getDate()); //output: "27"
mlptoday.year = d.getFullYear(); //output: "2013"
mlptoday.month = checkTime(d.getMonth()+1); //output: "01"
}
function checkTime(i) { if (i<10){i="0" + i} return i }
In a different function, I would like to check if the date the user gives as input is either the same day, or after the given day.
An example input may be: 2013.01.27.
I use this snippet of code to achieve what I want:
var remTime = "2013.01.27"; //user input
var remTimeArray = remTime.split('.') //output: ["2013","01","27"]
if (
!(remTimeArray[0] >= parent.mlptoday.year &&
remTimeArray[1] >= parent.mlptoday.month) ||
!((remTimeArray[1] == parent.mlptoday.month) ? Boolean(remTimeArray[2]*1 >= parent.mlptoday.date) : true)
){
//the input date is in the past
}
As you could probably guess, this does not work. The conditional statement seems to fail me, because if I invert Boolean(...) with an !(...), it will never fire the error, otherwise it always will.
Here's a snippet, where it works at it should:
var mlptoday = {};
var timer = setTimeout(today,500);
function today(){
var d = new Date();
mlptoday.year = d.getFullYear(); //output: "2013"
mlptoday.month = checkTime(d.getMonth()+1); //output: "01"
mlptoday.date = checkTime(d.getDate()); //output: "27"
$('#values').html(JSON.stringify(mlptoday));
}
function checkTime(i) { if (i<10){i="0" + i} return i }
$(document).ready(function(){
$('form').submit(function(e){
e.preventDefault();
var remTime = $('input').val(); //user input
var remTimeArray = remTime.split('.') //output: ["2013","01","27"]
if (
!(remTimeArray[0] >= mlptoday.year &&
remTimeArray[1] >= mlptoday.month) ||
!((remTimeArray[1] == mlptoday.month) ? Boolean(remTimeArray[2]*1 >= mlptoday.date) : true)
){
$('#past').fadeIn('fast').delay(500).fadeOut('fast');
}
})
})
#past { display:none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form>
<input type="text" id="input" required autocomplete="off" placeholder="yyyy.mm.dd" pattern="^(19|20)\d\d[.](0[1-9]|1[012])[.](0[1-9]|[12][0-9]|3[01])$" required="" />
<button>Check</button>
</form>
<pre id="values"></pre>
<span id="past">the input date is in the past</span>
I need a better way to do this, and I don't want to use any date picker plugins.
I would compare the dates as integers to avoid complex logic.
var todayConcat = "" + parent.mlptoday.year + parent.mlptoday.month + parent.mlptoday.date;
var remTimeConcat = remTime.replace(/\./g, "");
if (remTimeConcat < todayConcat) {
//the input time is in the past
}
Just make sure the dates and months always have the leading zero.

Categories