I'm trying to crate a datepicker from jQuery.
Users will allow to choose only June to September in each year from 2016-2020.
(So I don't think minDate and maxDate will work here)
I tried using the "beforeShowDay" as mentioned in
Disable specific months JqueryUI datepicker
The code was successfully disable users from picking the date outside from June to September but they can still choose January-December from the month dropdownlist (of datepicker).
What I want to do is limit the datepicker month-drop-down-list to show only June to September.
$(document).ready(function() {
$("#datepicker").datepicker({
changeMonth: true,
changeYear: true,
yearRange:'2016:2020',
minDate:0,
beforeShowDay: disableSpecificWeekDays
});
var monthsToDisable = [0,1,2,3,4,9,10,11];
var endMonth=[8];
function disableSpecificWeekDays(date) {
var month = date.getMonth();
if ($.inArray(month, monthsToDisable) !== -1) {
return [false];
}
return [true];
}
$("#datepicker").datepicker("setDate",'06/01/2016');
});
I don't see any options that would allow you to adjust this. I have a hacky solution that will probably do the job for most use cases, but that's your call. What I have done here is remove the unwanted select items from the datepicker list each time it gets updated. I had to add a short delay as jQuery UI takes a second to generate its code.
var removeDisabledMonths = function() {
setTimeout(function() {
var monthsToDisable = [0,1,2,3,4,9,10,11];
$.each(monthsToDisable, function(k, month) {
var i = $('#ui-datepicker-div select.ui-datepicker-month').find('option[value="'+month+'"]').remove();
});
}, 100);
};
//datepicker
$("#datepicker").datepicker({
changeMonth: true,
changeYear: true,
yearRange:'2016:2020',
minDate:0,
beforeShowDay: disableSpecificWeekDays,
// Added this --
onChangeMonthYear: function(year, month, obj) {
removeDisabledMonths();
}
});
//initial hide
setTimeout(function() {
removeDisabledMonths();
}, 1000);
Note that I had to call the function with a 1 second delay after the datepicker was initialized in order to get the months to hide the first time. Hacky, but if you are only looking to adjust the UI for the user, it just may do the job.
Well, Christ's code will activate itself after you choose some month/date.
If you don't, the January,Feb..... still being shown.
Therefore I add "beforeShow:" and connect it to removeDisabledMonths();
Now it works better.
$("#datepicker").datepicker({
changeMonth: true,
changeYear: true,
yearRange:'2016:2020',
minDate:0,
beforeShowDay: disableSpecificWeekDays,
onChangeMonthYear: function(year,month,obj){
removeDisabledMonths();
}
});
var monthsToDisable = [0,1,2,3,4,9,10,11];
function disableSpecificWeekDays(date) {
var month = date.getMonth();
var day=date.getDate();
if ($.inArray(month, monthsToDisable) !== -1) {
return [false];
}
return [true];
}
$("#datepicker").datepicker("setDate",'06/01/2016');er code here
$( ".selector" ).datepicker( "option", "defaultDate", "2019-09-01" );
$( ".selector" ).datepicker( "option", "minDate","2019-09-01");
$( ".selector" ).datepicker( "option", "maxDate","2019-09-30");
This displays only the month of September in the calendar and stops the user from accessing other months.
Related
I've read a lot of different answers to this, but I'm curious as to why my specific way of doing it (which I haven't found online) doesn't not render the desired results.
User selects deliverydate, after which pickupdate datepicker has a maxDate of 14 days from the deliverydate:
$( "#deliverydate" ).datepicker({
defaultDate: 1,
onClose: function( selectedDate ) {
$( "#pickupdate" ).datepicker( "option", "minDate", selectedDate, "defaultDate", selectedDate, "maxDate", (Date.parse(selectedDate) - Date.today())/1000/60/60/24 + 14 );
}
});
How I thought to run the calculation was calculate the number of days from today the selectedDate is and then add 14 (since maxDate can take an argument that's an integer representing the number of days from today).
Note I have Date.js
You can only use the datepicker("option", option, value) syntax for one single option. Since you are using multiple options for the $('#pickupdate') datepicker, you need to specify them as a JSON, as you did for $(#deliverydate). Like so:
$('#pickupdate').datepicker({
minDate: selectedDate,
defaultDate: selectedDate,
maxDate: ((Date.parse(selectedDate) - Date.today())/1000/60/60/24 + 14 )
});
See this JSFiddle for a working demonstration.
See also this Stack Overflow question about using jQuery Datepicker with multiple options.
Finally, you should consider changing to Moment.js. The last release of Date.js was 2007, so there hasn't been any major or minor releases to it for a long time.
OK after a ton of digging... ugh jQuery Datepicker is not doc'ed well.
Two important factoids:
1. Datepicker can only be initialized ONCE, thereafter in order to change the settings, you must use option
2. According to Datepicker, you should be able to provide multiple options in a map of option-value pairs, but nothing I do makes this work, and their docs looks just like single option, so ... whatever, I just set 3 options individually.
The way I got it to work is below:
$( "#deliverydate" ).datepicker({
defaultDate: 1, // 1 day from today
numberOfMonths: 1,
minDate: 0,
maxDate: <%= ENV["Days_in_advance"].to_i %>,
dateFormat: "M d, yy",
// despite the docs, it doesnt' look like you can set multiple options at once, so I'm doing it individually 3X below.
onClose: function( selectedDate ) {
deliverydate = Date.parse(selectedDate);
$( "#pickupdate" ).datepicker("option",
{ defaultDate: ((deliverydate - Date.today())/1000/60/60/24 + 1 ) });
// day after deliverydate
$( "#pickupdate" ).datepicker("option",
{ minDate: ((deliverydate - Date.today())/1000/60/60/24 ) });
// same day as deliverydate
$( "#pickupdate" ).datepicker("option",
{ maxDate: ((deliverydate - Date.today())/1000/60/60/24 + <%= ENV["Max_days_of_rental"].to_i %> )});
// upper limit on rental days
}
});
$( "#pickupdate" ).datepicker({
// this is triggered on DOM load and is overwritten the minute a deliverydate is selected per the onClose
defaultDate: 1, // 1 day from today
numberOfMonths: 1,
minDate: 0,
maxDate: <%= ENV["Max_days_of_rental"].to_i %>,
dateFormat: "M d, yy"
});
I am using jquery datepicker to show a calendar.Now as per my requirement i want to get the date selected by the user in my jquery variable which i will use in my application but i am not able to get the date ..
Here is the code for datepciker
<div id="datepicker"></div>
and here i am trying to get the selected code..
$(document).ready(function () {
$("#datepicker").datepicker({
onSelect: function (dateText, inst) {
var date = $(this).val();
alert(date);
}
});
});
But, I am not able to get the date ..Please help me ..Thanks..
This should do the trick
$(function() {
$("#datepicker").datepicker();
$("#datepicker").on("change",function(){
var selected = $(this).val();
alert(selected);
});
});
It's basic but here is a jsfiddle with it alerting the selected date when selected
update to change the date format
$(function() {
$( "#datepicker" ).datepicker({ dateFormat: "yy-mm-dd" });
$("#datepicker").on("change",function(){
var selected = $(this).val();
alert(selected);
});
});
jsfiddle
3rd update
$(function() {
$("#datepicker").datepicker({
dateFormat: "yy-mm-dd",
onSelect: function(){
var selected = $(this).val();
alert(selected);
}
});
});
I have used a little more of the native markup for datepicker ui here try this and see if you get the alert as you are after.
4th Update
$(function() {
$("#datepicker").datepicker({
dateFormat: "yy-mm-dd",
onSelect: function(){
var selected = $(this).datepicker("getDate");
alert(selected);
}
});
});
The 4th method uses $(this).datepicker("getDate") instead of $(this).val() as $(this).datepicker("getDate") returns a date object and $(this).val() returns the date as a string.
Depending on your needs select which one is appropriate.
(Added 4th method and explanation of the difference after #TimothyC.Quinn commented that the getDate being the correct method)
Though, question is answered, for people who just want a date object or set a date with specific format. There is simple functions jQuery provides. Here's working jsfiddle
$( "#datepicker" ).datepicker({ dateFormat: "dd-mm-yy" });
$("#datepicker").datepicker('setDate', '10-03-2020');
// pass string of your format or Date() object
$("#datepicker").datepicker('getDate');
// returns Date() object
$("#another_datepicker").datepicker('setDate', $("#datepicker").datepicker('getDate'));
// pass string of your format or Date() object
Try
$("#datepicker").datepicker({
onSelect:function(selectedDate)
{
alert(selectedDate);
}
});
OR
$("#datepicker").datepicker({
onSelect:function (dateText, inst)
{
alert(inst);
}
});
try this
$('.selector').datepicker({
onSelect: function(dateText, inst) { ... }
})
you have two elements with the class .datepicker, the selector won't know which element to choose from. So, you'll have to specify the name of the input you're trying to get the date from
first = $(".datepicker[name=datepicker1]").datepicker('getDate');
second = $(".datepicker[name=datepicker2]").datepicker('getDate');
You can use the changeDate event outlined here instead of onSelect and then reference e.date or e.dates. See the JSON below.
HTML:
<div id='QA'></div>
<div id='datepicker'></div>
JS:
<script type="text/javascript">
$(function() {
$('#datepicker').datepicker({
clearBtn: true,
todayHighlight: false,
multidate: true
}) .on('changeDate', function(e){
$('#QA').html(JSON.stringify(e));
});
});
/*
{
"type":"changeDate",
"date":"2015-08-08T07:00:00.000Z",
"dates":[
"2015-08-08T07:00:00.000Z"
],
"timeStamp":1438803681861,
"jQuery21409071635671425611":true,
"isTrigger":3,
"namespace":"",
"namespace_re":null,
"target":{
},
"delegateTarget":{
},
"currentTarget":{
},
"handleObj":{
"type":"changeDate",
"origType":"changeDate",
"guid":52,
"namespace":""
}
}
*/
</script>
The ideal way is to get the date and convert it to a common format and utilize the same. (may passing to server or so.)
$("#datepicker").datepicker('getDate').toISOString()
so it will get the date in ISO stander.
All code is for Bootstrap Datepicker
var calendar = $('#calendar').datepicker("getDate"); // Ex: Tue Jun 29 2021 00:00:00 GMT+0600 (Bangladesh Standard Time)
or
var calendar = $('#calendar').data('datepicker').getFormattedDate('yyyy-mm-dd'); // Ex: 2021-06-30
if(calendar){
alert(calendar);
} else {
alert('null');
}
If you need it in specific format like '2021/09/28':
$.datepicker.formatDate('yy/mm/dd',
$('.date-picker-2').datepicker("getDate")
);
Here is how to get Date object from datepicker in the onSelect event:
$("#datepickerid").datepicker({
onSelect: function (dateText, inst) {
var date_obj = $(this).datepicker('getDate');
}
});
I find it strange that the onSelect caller would not return the date object by default.
I have two date range forms. Each form has 2 fields, a from and to. In the javascript I have created two instances of the date range datepicker but for some reason, in the second date range form, it doesn't quite work right.
The first form works perfectly. But when I select a date in the from box in the second form, 9th October for example it displays that in the from box. When I then click into the to field in the second form, the furthest date I can select is 9th Oct for some reason?
I have a JS Fiddle below so you can see what is going on. I've searched around but I cannot find any working examples of two date-range forms. I can find a lot of default date pickers, but they're of course not date ranges and written different and the usual problem with them is people using the same IDs, however mine are all different so I don't get it..
JS Fiddle - http://jsfiddle.net/6jJ36/
Working Demo http://jsfiddle.net/fxr5c/
Culprit was: var option = this.id == "invfrom" ? "minDate" : "maxDate", line of code in your old code you had id wrong i.e. ivnfrom which inversed the behavior.
Rest this should help your cause :)
Code
var dates = $("#from, #to").datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3,
dateFormat: 'dd/mm/yy',
onSelect: function (selectedDate) {
var option = this.id == "from" ? "minDate" : "maxDate",
instance = $(this).data("datepicker"),
date = $.datepicker.parseDate(
instance.settings.dateFormat || $.datepicker._defaults.dateFormat,
selectedDate, instance.settings);
dates.not(this).datepicker("option", option, date);
}
});
var invdates = $("#invfrom, #invto").datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3,
dateFormat: 'dd/mm/yy',
onSelect: function (selectedDate) {
var option = this.id == "invfrom" ? "minDate" : "maxDate",
instance = $(this).data("datepicker"),
date = $.datepicker.parseDate(
instance.settings.dateFormat || $.datepicker._defaults.dateFormat,
selectedDate, instance.settings);
invdates.not(this).datepicker("option", option, date);
}
});
I am trying to check if a date is older than today's date & show an error if true. What is currently happening is if the month is less than today's month, the error is showing even if the year is set to 2014 or beyond. For example today is 4/18/2013 which doesn't have an error, but 4/17/2014 & 3/17/2014 get errors but 5/17/2013 does not. It seems the year is being ignored during the check. Hope that made a little sense...
$("#expDate").datepicker({
changeMonth: true,
changeYear: true,
minDate: 0,
onClose: function(selectedDate) {
var currDate = $.datepicker.formatDate('mm/dd/yy', new Date());
if (selectedDate < currDate) {
$("#warning").append("The number has expired");
} else {
$("#warning").html("");
}
}
});
You can do it directly with maxDate option
$("#datepicker").datepicker({ maxDate: new Date() });
Please take a look at http://jsfiddle.net/4bML8/
Everything is working fine (i think) except the fact that the datepicker doesn't disappear when I pick a date. Can anyone tell me what is causing this?
You never declared the variable dates but you used it. Create a variable dates and check this code
var dates = $('#d_date, #a_date').datepicker({
numberOfMonths: 1,
minDate: +1,
dateFormat: 'd / m / yy',
onSelect: function( selectedDate ) {
var option = this.id == "from" ? "minDate" : "maxDate",
instance = $( this ).data( "datepicker" ),
date = $.datepicker.parseDate(
instance.settings.dateFormat ||
$.datepicker._defaults.dateFormat,
selectedDate, instance.settings );
dates.not( this ).datepicker( "option", option, date );
}
});
If you want the datepicker to close after it enters a date, you need to tell it to move focus out of the current field. I do it this way:
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd',
firstDay: 1,
changeMonth:true,
changeYear: true,
onClose: function(dateText, inst) {
$(this).focus(); //set focus and then move to next field so validator will fire
$(this).focusNextInputField(); //causes datepicker to close
}
});