I am trying to show an alert when someone selects a date in the past:
jQuery('#date').datepicker().change(evt => {
var selectedDate = jQuery('#date').datepicker('getDate');
var theSelectedDate = selectedDate.setHours(0,0,0,0);
var now = new Date();
var theNow = now.setHours(0,0,0,0);
if (theSelectedDate > theNow) {
// Date in in the future, all good
} else {
alert("Selected date is in the past");
}
});
..and the date field...
<input type="date" id="date" name="date" />
The problem is that regardless of what date I chose with the date picker, the alert is always 'Selected date is in the past' on mobile devices.
What the heck am I doing wrong?
I am not sure why you do not set the Min Date so that Users cannot select a past date.
$(function() {
$("#date").datepicker({
minDate: "+1d"
});
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<p>Date: <input type="text" id="date"></p>
You can use 0 for today or +1d to exclude today.
Update
For Native HTML5 datepicker, you can leverage the min attribute.
You can use the min and max attributes to restrict the dates that can be chosen by the user.
$(function() {
function nowStr() {
var dt = new Date();
var yy = dt.getFullYear();
var m = (dt.getMonth() + 1);
m = m < 10 ? "0" + m : m;
var d = dt.getDate();
d = d < 10 ? "0" + d : d;
var s = yy + "-" + m + "-" + d;
return s;
}
$("#date").attr("min", nowStr());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="date" id="date" name="date" min="2019-01-01" />
Try this.
I have shifted now above the selected date
jQuery('#date').datepicker().change(evt => {
var now = new Date();
var selectedDate = jQuery('#date').datepicker('getDate');
var theSelectedDate = selectedDate.setHours(0,0,0,0);
var theNow = now.setHours(0,0,0,0);
if (theSelectedDate >= theNow) {
alert("Selected date is correct !!!!!!!");
// Date in in the future, all good
} else {
alert("Selected date is in the past");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"/>
<input type="text" class="form-control" id="date" name="date" placeholder="DD/MM/YYY">
Your looking for the onSelect event:
$("#date").datepicker({
onSelect: function(dateText, inst) {
var selectedDate = new Date(dateText);
var theSelectedDate = selectedDate.setHours(0,0,0,0);
var now = new Date();
var theNow = now.setHours(0,0,0,0);
if (theSelectedDate > theNow) {
console.log(true);
// Date in in the future, all good
} else {
console.log(false);
alert("Selected date is in the past");
}
}
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js" type="text/javascript"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="Stylesheet" type="text/css" />
<input type="date" id="date" name="date" />
See this answer
Related
I am trying to check if a see if this date picker (pickadate.js) has selected the current day on set. Here is my code:
var today = new Date();
var tomorrow = new Date();
tomorrow.setDate(today.getDate() + 1);
var nextyear = new Date();
nextyear.setFullYear(nextyear.getFullYear() + 1);
var pickupdatepicker = $("#car-rental-pickup-date").pickadate({
editable: true,
format: "mm/dd/yyyy",
min: today,
max: nextyear,
today: "",
close: "",
clear: "",
onSet: function(context) {
var d = new Date(context.select);
dnotime = new Date(d.toDateString());
todaynotime = new Date(today.toDateString());
var currenthour = new Date().getHours();
var hourp3 = currenthour + 13;
console.log (dnotime);
console.log (todaynotime);
if (dnotime == todaynotime) {
time.set({
disable: [
{ from: [0,0], to: [hourp3,00] }
]
});
console.log ("today!");
}else{
console.log ("not today!");
}
}
});
<link rel="stylesheet" href="https://amsul.ca/pickadate.js/vendor/pickadate/lib/themes/default.date.css" id="theme_date">
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://amsul.ca/pickadate.js/vendor/pickadate/lib/picker.js"></script>
<script src="https://amsul.ca/pickadate.js/vendor/pickadate/lib/picker.date.js"></script>
<input type="date" name="car-rental-pickup-date" id="car-rental-pickup-date" class="form-control tleft readonly" value="" placeholder="Select Pickup Date" required>
But the if statement comparing the two dates isn't working but the console says they are identical. What gives? Can someone check this out and tell me what I am doing wrong?
In your code:
if (dnotime == todaynotime) {
compares two Date objects, so it's always false. Coerce to number first:
if (+dnotime == +todaynotime) {
However, you can make it simpler than that as context.select returns a time value for the local start of the selected date, so you can do:
if (context.select == new Date().setHours(0,0,0,0))
and simplify the preceding code. Here's the original code modified to work:
var today = new Date();
// Set to start of day
today.setHours(0,0,0,0);
// Copy today as root for tomorrow
var tomorrow = new Date(today);
tomorrow.setDate(today.getDate() + 1);
// And for next year
var nextyear = new Date(today);
nextyear.setFullYear(nextyear.getFullYear() + 1);
var pickupdatepicker = $("#car-rental-pickup-date").pickadate({
editable: true,
format: "mm/dd/yyyy",
min: today,
max: nextyear,
today: "",
close: "",
clear: "",
onSet: function(context) {
// Could keep value as number, but OK as Date too
var d = new Date(context.select);
// This is unnecessary
// dnotime = new Date(d.toDateString());
// todaynotime = new Date(today.toDateString());
// Not relevant to issue
// var currenthour = new Date().getHours();
// var hourp3 = currenthour + 13;
// Compare time values
// Could also do: if (+d == + today) {...}
if (d.getTime() == today.getTime()) {
/* Not relevant
time.set({
disable: [
{ from: [0,0], to: [hourp3,00] }
]
});
*/
console.log ("today!");
} else {
console.log ("not today!");
}
}
});
<link rel="stylesheet" href="https://amsul.ca/pickadate.js/vendor/pickadate/lib/themes/default.date.css" id="theme_date">
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://amsul.ca/pickadate.js/vendor/pickadate/lib/picker.js"></script>
<script src="https://amsul.ca/pickadate.js/vendor/pickadate/lib/picker.date.js"></script>
<input type="date" name="car-rental-pickup-date" id="car-rental-pickup-date" class="form-control tleft readonly" value="" placeholder="Select Pickup Date" required>
How do I compare 2 values? I managed to compare the two values, but I can not get the right date. In addition, I want to add a class exactly to the date that is in the array. I use air-datepicker, and I want to designate certain dates from the array in a different color and disabled. Who can tell me how to do this?
Hhow to prohibit the choice of a date, if there is a reserve between them ?
$(document).ready(function () {
var disabledDates = ['2018-5-20', '2018-5-21', '2018-5-22', '2018-5-23'];
var $startDate = $('#start');
var $endDate = $('#end');
$startDate.datepicker({
inline: false,
range: true,
toggleSelected: true,
minDate: new Date(),
multipleDatesSeparator: ",",
dateFormat: 'dd-mm-yyyy',
onSelect: function (fd, date) {
if(date){
var arrDate = fd.split(",");
$startDate.val(arrDate[0]);
$endDate.val(arrDate[1]);
if(arrDate[1]){
$('.datepicker').css("left", "-100000px");
$startDate.blur();
}
$endDate.on('click', function () {
$startDate.datepicker().val(arrDate[0]).data('datepicker').show();
});
}
},
onRenderCell: function(date, cellType) {
var formatted = getFormattedDate(date);
if (cellType == 'day') {
var returnDay = {
disabled: false
};
var selectedDate = disabledDates.filter(function(date){
return date == formatted;
}).length;
if( selectedDate > 0 || disabledDates[0] <= formatted && formatted <= disabledDates[1]){
returnDay = {
disabled: true
};
}
return returnDay;
}
}
});
function getFormattedDate(date) {
var year = date.getFullYear(),
month = date.getMonth() + 1,
date = date.getDate();
return year + '-' + month + '-' + date;
}
});
.reservation-calendar {
display: flex;
padding: 20px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/air-datepicker/2.2.3/css/datepicker.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/air-datepicker/2.2.3/js/datepicker.js"></script>
<div class="reservation-calendar">
<div class="reservation-calendar__item line">
<input class="start" type="text" id="start">
</div>
-
<div class="reservation-calendar__item">
<input class="start" type="text" id="end">
</div>
</div>
You may just return the class you want and make it disable when you found it in the array.
$(document).ready(function () {
var disabledDates = ['2018-5-30', '2018-6-3'];
var $start = $('#start');
var $end = $('#end');
$start.datepicker({
inline: false,
range: true,
toggleSelected: true,
minDate: new Date(),
multipleDatesSeparator: ",",
dateFormat: 'dd-mm-yyyy',
onSelect: function (fd, date) {
if(date){
var arr = fd.split(",");
$start.val(arr[0]);
$end.val(arr[1]);
if(arr[1]){
$('.datepicker').css("left", "-100000px");
$start.blur();
}
$end.on('click', function () {
$start.datepicker().val(arr[0]).data('datepicker').show();
});
}
},
onRenderCell: function(date, cellType) {
var formatted = getFormattedDate(date);
console.log(formatted);
if (cellType == 'day') {
let returnDay = {
classes: 'my-class',
disabled: false
};
var ab = disabledDates.filter(function(date){
return date == formatted;
}).length;
console.log(ab);
if( ab > 0){
returnDay = {
classes: 'class-you-want-to-add-to-disable-day',
disabled: true
};
}
return returnDay;
}
}
});
function getFormattedDate(date) {
var year = date.getFullYear(),
month = date.getMonth() + 1,
date = date.getDate();
return year + '-' + month + '-' + date;
}
});
.reservation-calendar {
display: flex;
padding: 20px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/air-datepicker/2.2.3/css/datepicker.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/air-datepicker/2.2.3/js/datepicker.js"></script>
<div class="reservation-calendar">
<div class="reservation-calendar__item line">
<input class="start" type="text" id="start">
</div>
-
<div class="reservation-calendar__item">
<input class="start" type="text" id="end">
</div>
</div>
I created a validation to check if a person is less than 18 years of age. If the person is less than 18 years of age a dialog box opens. I'm using JQuery UI dialog-box to do this, but the dialog-box looks messed up (see picture). I don't know what i'm doing wrong here. How do i make the dialog box display correctly?
function myFunction() {
today = new Date();
todayYear = today.getFullYear();
todayMonth = today.getMonth();
todayDay = today.getDay();
var x = document.getElementById("DOB").value;
birthDate = new Date(x);
birthYear = birthDate.getFullYear();
birthMonth = birthDate.getMonth();
birthDay = birthDate.getDay();
age = todayYear - birthYear;
if (todayMonth < birthMonth - 1 ){
age--;
}
if (age < 18){
$( function() {
$('<div></div>').dialog({
modal: true,
title: "Age Check?",
open: function () {
var markup = 'Applicant is not 18 years old. Do you wish to continue?';
$(this).html(markup);
},
buttons: {
'Confirm': function() {
$(this).dialog('close');
},
'Change': function() {
$('#DOB').val('');
$(this).dialog('close');
}
}
});
} );
}
}
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<input name="DOB" onchange="myFunction()" type="date" class="form-control" id="DOB" required style=Width:60%; position:relative; placeholder="MM/DD/YYYY">
jquery-ui.css is missing
function myFunction() {
today = new Date();
todayYear = today.getFullYear();
todayMonth = today.getMonth();
todayDay = today.getDay();
var x = document.getElementById("DOB").value;
birthDate = new Date(x);
birthYear = birthDate.getFullYear();
birthMonth = birthDate.getMonth();
birthDay = birthDate.getDay();
age = todayYear - birthYear;
if (todayMonth < birthMonth - 1 ){
age--;
}
if (age < 18){
$( function() {
$('<div></div>').dialog({
modal: true,
title: "Age Check?",
open: function () {
var markup = 'Applicant is not 18 years old. Do you wish to continue?';
$(this).html(markup);
},
buttons: {
'Confirm': function() {
$(this).dialog('close');
},
'Change': function() {
$('#DOB').val('');
$(this).dialog('close');
}
}
});
} );
}
}
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<link href="//code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" rel="stylesheet" type="text/css">
<script src="//code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
<script src="//code.jquery.com/ui/1.9.2/jquery-ui.js" type="text/javascript"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" type="text/javascript"></script>
<input name="DOB" onchange="javascript:myFunction()" type="date" class="form-control" id="DOB" required style=Width:60%; position:relative; placeholder="MM/DD/YYYY">
I am making a countdown counter where the user is entering the start date and duration and then the End date gets calculated. And based on this End date a countdown counter starts.
But the issue here is that the counter is giving the wrong output. The number of months, days, hours, min, sec everything is fine except the year.
I think there is something wrong with my srftime command.
<script src="external/jquery/dateFormat.min.js" type="text/javascript"></script>
<script src="external/jquery/jquery.countdown.min.js" type="text/javascript"></script>
<script src="jquery-ui.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#start_date").datepicker({ minDate: 0 });
$("#setCounter").on("click",function(){
var startDate = $("#start_date").val();
var duration = $("#period").val();
if (startDate == "" || duration == "") {
alert("Please fill all the fields.");
return;
}
stopDate = new Date(startDate);
stopDate.setMonth(stopDate.getMonth() + parseInt(duration));
stopDate = DateFormat.format.date(stopDate,"MM/dd/yyyy");
$("#end_date label").html(stopDate);
$("#end_date").show();
var today = DateFormat.format.date(new Date(),"MM/dd/yyyy");
todayObj = new Date(today);
startDateObj = new Date(startDate);
todayTimestamp = Date.UTC(todayObj.getFullYear(),todayObj.getMonth(), todayObj.getDate());
startDateTimestamp = Date.UTC(startDateObj.getFullYear(),startDateObj.getMonth(), startDateObj.getDate());
if (todayTimestamp >= startDateTimestamp) {
$('#getting-started').countdown(stopDate, function(event) {
$(this).html(event.strftime('%Y year %m month %d days %H:%M:%S'));
});
};
});
});
</script>
My html code is as follows:
<div>
<p>Start Date: <input type="text" id="start_date"></p>
<p>Period: <input type="text" id="period" placeholder="No. of Months"></p>
<p id="end_date">End Date: <label></label></p>
<p><input type="button" value="Add Counter" id="setCounter" /></p>
</div>
<div id="getting-started"></div>
I am very new to JQuery and JS and I wrote a small GUI in php where the user has to choose two week numbers and I have a function that produces some stats about it. I found a JS code that highlights the whole week when the user go through it but when clicking on one of the dates, the specific date is being inserted to the input box. I would like to put the week number in the input box instead. Is this possible?
The code I use was posted here:
http://jsfiddle.net/MqD2n/
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" media="screen" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css">
<script type="text/javascript">
$(function() {
var startDate;
var endDate;
var selectCurrentWeek = function () {
window.setTimeout(function () {
$('.ui-weekpicker').find('.ui-datepicker-current-day a').addClass('ui-state-active').removeClass('ui-state-default');
}, 1);
}
var setDates = function (input) {
var $input = $(input);
var date = $input.datepicker('getDate');
if (date !== null) {
var firstDay = $input.datepicker( "option", "firstDay" );
var dayAdjustment = date.getDay() - firstDay;
if (dayAdjustment < 0) {
dayAdjustment += 7;
}
startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - dayAdjustment);
endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - dayAdjustment + 6);
var inst = $input.data('datepicker');
var dateFormat = inst.settings.dateFormat || $.datepicker._defaults.dateFormat;
$('#startDate').text($.datepicker.formatDate(dateFormat, startDate, inst.settings));
$('#endDate').text($.datepicker.formatDate(dateFormat, endDate, inst.settings));
}
}
$('.week-picker').datepicker({
beforeShow: function () {
$('#ui-datepicker-div').addClass('ui-weekpicker');
selectCurrentWeek();
},
onClose: function () {
$('#ui-datepicker-div').removeClass('ui-weekpicker');
},
showOtherMonths: true,
selectOtherMonths: true,
onSelect: function (dateText, inst) {
setDates(this);
selectCurrentWeek();
$(this).change();
},
beforeShowDay: function (date) {
var cssClass = '';
if (date >= startDate && date <= endDate)
cssClass = 'ui-datepicker-current-day';
return [true, cssClass];
},
onChangeMonthYear: function (year, month, inst) {
selectCurrentWeek();
}
});
setDates('.week-picker');
var $calendarTR = $('.ui-weekpicker .ui-datepicker-calendar tr');
$calendarTR.live('mousemove', function () {
$(this).find('td a').addClass('ui-state-hover');
});
$calendarTR.live('mouseleave', function () {
$(this).find('td a').removeClass('ui-state-hover');
});
});
</script>
</head>
<body>
<input class="week-picker"></input>
<br /><br />
<label>Week :</label> <span id="startDate"></span> - <span id="endDate"></span>
</body>
</html>
Totally 2 fields are present. First field - datepicker is to select the date and the second field - weekNumberis to get the week number for that date.
<input type="text" id="datepicker" />
<input type="text" id="weekNumber" />
$('#datepicker').datepicker({
onSelect: function (dateText, inst) {
$('#weekNumber').val($.datepicker.iso8601Week(new Date(dateText)));
}
});
Here is the JS Fiddle Demo
Edit:
For displaying the week number in the same selecting date field
<input type="text" id="datepicker" />
$('#datepicker').datepicker({
onSelect: function (dateText, inst) {
$('#datepicker').val("");
$('#datepicker').val($.datepicker.iso8601Week(new Date(dateText)));
}
});
Demo is here