Disable button if input date is lesser than 4 months - javascript

I want to disable the next button when the input date is lesser than 4 months. Get the current date and check if the current date is lesser than 4 months. If it's lesser disable the next button and give an alert.
I tried it with an alert button to test the datepicker, but that didn't work:
jQuery(document).ready(function($) {
$('#input_18_104').datepicker({
onSelect: function() {
var date = $(this).datepicker('getDate');
var today = new Date();
if ((new Date(today.getFullYear(), today.getMonth(), today.getDate() + 120)) < date) {
//Do somthing here..
alert(123);
}
},
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/js/bootstrap-datepicker.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker.css" rel="stylesheet" />
<input name="input_104" id="input_18_104" type="text" class="datepicker medium mdy datepicker_no_icon hasDatepicker" tabindex="72" placeholder="Date?"> Next button:
<input type="button" id="next_button_18_94" class="form_next_button button" value="Next" tabindex="76">

Your actual condition is wrong today.getDate()+120 will give you a number higher than 120 which will lead to a wrong date then your comparison won't be always correct.
You need to compare the month values respectively, this is how you could do it:
$(document).ready(function () {
$('#input_18_104').datepicker()
.on("input change", function (e) {
var date = $(this).datepicker('getDate');
var today = new Date();
if ((today.getMonth() + 11) - (date.getMonth() + 11) > 4) {
alert("The date is wrong");
} else if (((today.getMonth() + 11) - (date.getMonth() + 11) == 4) && (today.getDate() > date.getDate())) {
alert("The date is wrong");
} else {
console.log("Date is fine");
}
});
});
Explanataion:
We used date.getMonth() + 11 to make sure we don't get a negative
value, so we added 11 to the 2 months values, so it won't affect
the test.
Then we check if the difference between these two values isn't higher than 4, so the choosen date is fine.
Demo:
$(document).ready(function() {
$('#input_18_104').datepicker()
.on("input change", function(e) {
var date = $(this).datepicker('getDate');
var today = new Date();
if ((today.getMonth() + 11) - (date.getMonth() + 11) > 4) {
alert("The date is wrong");
} else if (((today.getMonth() + 11) - (date.getMonth() + 11) == 4) && (today.getDate() > date.getDate())) {
alert("The date is wrong");
} else {
console.log("Date is fine");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/js/bootstrap-datepicker.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker.css" rel="stylesheet" />
<input name="input_104" id="input_18_104" type="text" class="datepicker medium mdy datepicker_no_icon hasDatepicker" tabindex="72" placeholder="Date?"> Next button:
<input type="button" id="next_button_18_94" class="form_next_button button" value="Next" tabindex="76">

The following approach will work
jQuery(document).ready(function($) {
$("#input_18_104").datepicker({
dateFormat: 'dd/mm/yy'}).on("changeDate", function (e) {
alert("Working");});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/js/bootstrap-datepicker.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker.css" rel="stylesheet" />
<input name="input_104" id="input_18_104" type="text" class="datepicker medium mdy datepicker_no_icon hasDatepicker" tabindex="72" placeholder="Date?"> Next button:
<input type="button" id="next_button_18_94" class="form_next_button button" value="Next" tabindex="76">

That is not too difficult.
new Date returns a timestamp in milliseconds. The date function is pretty smart. You can overflow the months and days and it will correct it to the date: so a value of 14 as month will actually become February or March. But you really want to stay away from day calculation or subtracting months because of leap years, 30 and 31 day count etc. Comparing time stamps is safer.
new Date(date)
Just add 4 months:
//remember month is zero based, so correct with +1 to give correct date input.
future = new Date(today.getFullyear()+"-"+(today.getMonth()+1+4)+"-"+today.getDate())
Now compare:
future < new Date(date);
When the selected date is bigger than the future 4 month date it will be more than 4 months.
Under the hood JavaScript compares timestamps which are counted in milliseconds from 1970-01-01 so whenever a timestamp is bigger than another it is in the future relative to the compared timestamp.

I would compare the dates based on their time values. That's not 100% accurate because not all months have 30 days, but ok. Here's a quick try
jQuery(document).ready(function ($) {
$('#input_18_104').datepicker({
onSelect: function(){
var date = $(this).datepicker('getDate');
var today = new Date();
var threshold = 10368000000; // 120d in ms = 4*30*24*60*60*1000
var d = today.getTime()-date.getTime();
//console.log(d, d > threshold)
// be optimistic...
$('#next_button_18_94').attr('disabled', false);
if (d < 0) {
// selected date is in the future => everything ok
return;
}
if (d > threshold) {
// oops, selected date more than 4 months in the past
$('#next_button_18_94').attr('disabled', true);
return;
}
},
});
});
#next_button_18_94[disabled]{
border: 2px solid red;
}
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<input name="input_104" id="input_18_104" type="text" tabindex="72" >
<input type="button" id="next_button_18_94" class="form_next_button button" value="Next" tabindex="76">

Assuming that "lesser than 4 months" mean means the input date is less than 4 months before today, then a simple method is to add 4 months to the input date and see if it's less than today, then enable or disable the button as required, e.g.
function checkDate(input) {
var form = input.form;
var now = new Date();
var then = parseDate(input.value);
addMonths(then, 4);
form.actionButton.disabled = now > then;
}
function parseDate(s) {
var b = s.split(/\D/)
return new Date(b[0], b[1]-1, b[2]);
}
function addMonths(date, months) {
var d = date.getDate();
date.setMonth(date.getMonth() + +months);
if (date.getDate() != d) date.setDate(0);
return date;
}
<form>
Date (yyyy-mm-dd)<input type="text" value="2017-01-01" name="date" onblur="checkDate(this)"><br>
<input type="button" name="actionButton" onclick="console.log(this.form.date.value)" value="Do stuff" disabled>

Use monthDiff function
jQuery(document).ready(function ($) {
$('#input_18_104').datepicker({
onSelect: function () {
var date = $(this).datepicker('getDate');
var today = new Date();
if (monthDiff(today, date) < 4) {
//Do somthing here..
alert(123);
}
},
});
});
function monthDiff(d1, d2) {
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth() + 1;
months += d2.getMonth();
return months <= 0 ? 0 : months;
}

Related

How to disable all days in month except 2nd and 4th week's Thursday in Kendodatepicker

I am using kendodatepicker in HTML form for selecting dates.
I want to make all dates of every month disabled and only show the 2nd and 4th weeks Thursday only to be selectable (means the user can select only 2days in a month that is Thursday).
How can I achieve that using kendodatepicker,
I searched a lot on the internet but did not find something useful.
currently, I am using the function for this as:--
$("#datepicker").kendoDatePicker({
format: "dd/MM/yyyy",
min: yesterday,
disableDates: ["mo","tu","we","sa","su","fr",],
});
One of the overloads of the disabledDates method is to accept a function. What you can do is:
Check if the date is a thursday
Check if the date falls on the second or fourth week of the month
If both one and two are true, then return false
Here is a nifty function that gets the week of the month for a given date to help with number 2: https://stackoverflow.com/a/36036273/1920035
Here is an example:
const getWeekOfMonth = (date) => {
var firstWeekday = new Date(date.getFullYear(), date.getMonth(), 1).getDay() - 1;
if (firstWeekday < 0) {
firstWeekday = 6;
}
var offsetDate = date.getDate() + firstWeekday - 1;
return Math.floor(offsetDate / 7);
};
$("#datepicker").kendoDatePicker({
value: new Date(),
disableDates: (date) => {
date = new Date(date);
const dayOfWeek = date.getDay();
const weekOfMonth = getWeekOfMonth(date);
return !(dayOfWeek === 4 && (weekOfMonth === 1 || weekOfMonth === 3));
}
});
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2022.1.301/styles/kendo.default-v2.min.css"/>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2022.1.301/js/kendo.all.min.js"></script>
<input id="datepicker" />

How do I get my HTML form date input to only allow specific days of the week to be chosen using JavaScript, React and HTML?

I am trying to get my Forms Date Input to only allow Thursday, Friday, and Saturday to be selected. But I can't seem to find a way to do it.
Is there some JavaScript or HTML code I could use to solve this issue?
Here is my current code
import React from 'react';
const CustomForm = () => {
const addTwoWeeks = function () {
let today = new Date();
today.setDate(today.getDate() + 14);
let dd = today.getDate();
let mm = today.getMonth() + 1;
let yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
today = yyyy + '-' + mm + '-' + dd;
return today;
}
return (
<form>
<label htmlFor="date">Pick-Up Date:</label>
<input type="date" id="date" name="date" min={addTwoWeeks()} required />
</form>
)
}
export default CustomForm;
It's quite simple if you will use datepicker js
$("#datepicker").datepicker({
beforeShowDay: function (d) {
var day = d.getDay();
return [day != 0 && day != 1 && day != 2 && day != 3];
},
});
Full working example:
<html>
<head>
<title>HTML</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/themes/smoothness/jquery-ui.css" crossorigin="anonymous" referrerpolicy="no-referrer"/>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js" crossorigin="anonymous" referrerpolicy="no-referrer" ></script>
<script>
$(function () {
$("#datepicker").datepicker({
beforeShowDay: function (d) {
var day = d.getDay();
return [day != 0 && day != 1 && day != 2 && day != 3];
},
});
});
</script>
</head>
<body>
<input type="text" id="datepicker" />
</body>
</html>
The <input type="date" /> does not allow disabling specific days of the week. See here (MDN docs).
In that case, you can either
Prevent form submission and showing a proper validation message for the invalid day selection.
Or, use a third-party react date picker/calendar library (or, if you have time, implement a datepicker).
I recommend react-dates(Github link) in case you go for option 2. Keep in mind the size of the import though.
<SingleDatePickerWrapper isDayBlocked={isDayBlocked} autoFocus />
Here(Storybook) is a variant/example which blocks day selection for Fridays. Link to the corresponding code(Gtihub) .

How to check whether a date is disabled or not in Bootstrap Datepicker?

I have three <input> elements in my form.
<input id="from-date" type="text" class="form-control" placeholder="From">
<input id="to-date" type="text" class="form-control" placeholder="To">
<input id="total" class="form-control" placeholder="Total no. of days">
out of which first and second accepts a date chosen from Bootstrap Datepicker and the last one displays total number of days.
The total number of days is calculated excluding weekends( Saturdays and Sundays). I now want to achieve a functionality as in, when I disable a set of dates using datesDisabled option, those disabled dates should not be counted to form total no. of days. How to check whether a date is disabled in Bootstrap Datepicker ?
Here is a quick JS Fiddle to my code.
Below is my JS.
$(function() {
var date = new Date();
var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());
var end = new Date(date.getFullYear(), date.getMonth(), date.getDate());
// create the from date
$('#from-date').datepicker({
autoclose: true,
format: 'dd-mm-yyyy',
startDate: today,
daysOfWeekDisabled: [0,6],
datesDisabled:["12-04-2018","17-04-2018","19-04-2018"],
}).on('changeDate', function(ev) {
ConfigureToDate();
});
$('#to-date').datepicker({
autoclose: true,
format: 'dd-mm-yyyy',
daysOfWeekDisabled: [0,6],
datesDisabled:["12-04-2018","17-04-2018","19-04-2018"],
startDate: $('#from-date').val()
}).on('changeDate', function(ev) {
var fromDate = $('#from-date').data('datepicker').dates[0];
var get_no_of_days = getWorkingDatesCount(fromDate, ev.date);
var final_count = parseInt(get_no_of_days) + 1;//adding +1 to the total number of days to count the present date as well.
$('#total').val(final_count);
});
// Set the min date on page load
ConfigureToDate();
// Resets the min date of the return date
function ConfigureToDate() {
$('#to-date').val("").datepicker("update");
$('#to-date').datepicker('setStartDate', $('#from-date').val());
}
});
function getWorkingDatesCount(startDate, endDate) {
var count = 0;
var curDate = new Date(startDate);
while (curDate <= endDate) {
var dayOfWeek = curDate.getDay();
if ( !((dayOfWeek == 6) || (dayOfWeek == 0)) )
count++;
curDate.setDate(curDate.getDate() + 1);
}
return count;
}
If anyone could help me with this, it'll be of great help.
Working example: https://jsfiddle.net/cCrul/qLt6k0yv/
I just declared datesDisables as a variable:
var datesDisabled = ["12-04-2018", "17-04-2018", "19-04-2018"];
and I use it to check if curDate is in that array before executing count++:
if (
!((dayOfWeek == 6) || (dayOfWeek == 0)) &&
(datesDisabled.indexOf(formatDate(curDate)) == -1)
) {
count++;
}
formatDate() function defined in the jsfiddle code.
$(function() {
var date = new Date();
var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());
var end = new Date(date.getFullYear(), date.getMonth(), date.getDate());
var datesDisabled = ["12-04-2018", "17-04-2018", "19-04-2018"];
// create the from date
$('#from-date').datepicker({
autoclose: true,
format: 'dd-mm-yyyy',
startDate: today,
daysOfWeekDisabled: [0, 6],
datesDisabled: datesDisabled,
}).on('changeDate', function(ev) {
ConfigureToDate();
});
$('#to-date').datepicker({
autoclose: true,
format: 'dd-mm-yyyy',
daysOfWeekDisabled: [0, 6],
datesDisabled: datesDisabled,
startDate: $('#from-date').val()
}).on('changeDate', function(ev) {
var fromDate = $('#from-date').data('datepicker').dates[0];
var get_no_of_days = getWorkingDatesCount(fromDate, ev.date);
var final_count = parseInt(get_no_of_days) + 1; //adding +1 to the total number of days to count the present date as well.
$('#total').val(final_count);
});
// Set the min date on page load
ConfigureToDate();
// Resets the min date of the return date
function ConfigureToDate() {
$('#to-date').val("").datepicker("update");
$('#to-date').datepicker('setStartDate', $('#from-date').val());
}
function getWorkingDatesCount(startDate, endDate) {
var count = 0;
var curDate = new Date(startDate);
while (curDate <= endDate) {
var dayOfWeek = curDate.getDay();
if (!((dayOfWeek == 6) || (dayOfWeek == 0)) && (datesDisabled.indexOf(formatDate(curDate)) == -1)) {
console.log(formatDate(curDate));
count++;
}
curDate.setDate(curDate.getDate() + 1);
}
return count;
}
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [day, month, year].join('-');
}
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.standalone.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.min.js"></script>
<input id="from-date" type="text" class="form-control" placeholder="From">
<input id="to-date" type="text" class="form-control" placeholder="To">
<input id="total" class="form-control" placeholder="Total no. of days">

HTML5 datepicker prevent past dates [duplicate]

This question already has answers here:
Disable certain dates from html5 datepicker
(6 answers)
Closed 9 years ago.
I am working on a website for booking movie tickets. What should I set the min attribute to, to prevent past dates in the HTML5 datepicker? (I do not want to use PHP solution mentioned here.)
Is there a pure HTML5/Javascript solution for this?
When the document loads have the date input disabled. Run an onload function that inserts today's date into the min field in the required format.
function onLoad() {
var input = document.getElementById("dateField");
var today = new Date();
// Set month and day to string to add leading 0
var day = new String(today.getDate());
var mon = new String(today.getMonth()+1); //January is 0!
var yr = today.getFullYear();
if(day.length < 2) { day = "0" + day; }
if(mon.length < 2) { mon = "0" + mon; }
var date = new String( yr + '-' + mon + '-' + day );
input.disabled = false;
input.setAttribute('min', date);
}
document.addEventListener('load', onLoad, false);
<body>
<input id="dateField" type="date" disabled />
</body>
Here it is in a fiddle: http://jsfiddle.net/tj9Xh/2/
try this:
<input id="dateField" type="date"/>
var dt= new Date();
var yyyy = dt.getFullYear().toString();
var mm = (dt.getMonth()+1).toString(); // getMonth() is zero-based
var dd = dt.getDate().toString();
var min = yyyy +'-'+ (mm[1]?mm:"0"+mm[0]) +'-'+ (dd[1]?dd:"0"+dd[0]); // padding
alert(min);
$('#dateField').prop('min',min);

How to compare dates - JavaScript/ASP Classic [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript to compare two dates, from strings, begin <= end
Beginner. I have a HTML form with two date fields the user fills in either manually or by a calendar picker. Start Date and End Date. Before the form can be submitted I want to check to make sure the End Date entered is >= the Start Date entered. Using Dreamweaver. Any help with this is greatly appreciated. Thank you
Dates comparison:
function compareDates(date1, date2) {
var delta = date1.getTime() - date2.getTime();
if(delta == 0) {
return 0;
}
return delta > 0 ? 1 : -1;
}
Dates difference:
var startDate = new Date(),
endDate,
delta;
setTimeout(function() {
endDate = new Date();
delta = endDate.getTime() - startDate.getTime();
alert(delta + ' ms');
}, 1000);​
DEMO
Documentation
Try something like this (here is the Fiddle)
<script type="text/javascript">
function test(){
var dt1 = new Date(""+document.getElementById("dt1").value);
var dt2 = new Date(document.getElementById("dt2").value);
alert(dt2 > dt1);
}
</script>
<input id="dt1" type="text" value="09/25/2012"/>
<input id="dt2" type="text" value="09/24/2012"/>
<input id="btn" type="button" value="test" onclick="test()"/>

Categories