I'm using JSON to store data and using date range picker as the follows code.
$(function() {
$("#datepicker").datepicker({
beforeShowDay: function(date) {
var date1 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#input1").val());
var date2 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#input2").val());
return [true, date1 && ((date.getTime() == date1.getTime()) || (date2 && date >= date1 && date <= date2)) ? "dp-highlight" : ""];
},
onSelect: function(dateText, inst) {
var date1 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#input1").val());
var date2 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#input2").val());
if (!date1 || date2) {
$("#input1").val(dateText);
$("#input2").val("");
$(this).datepicker("option", "minDate", dateText);
} else {
$("#input2").val(dateText);
$(this).datepicker("option", "minDate", null);
}
//$("#dateoutput").html("Chosen date is <b>" + date1 + "</b> - <b>" + dateText + "</b>");
}
});
});
How can i bind data according to selected date range.
enter code here
I'm not entirely sure what it was you wanted to do, but I've made a JSFiddle from what I understood.
To test, do this:
1) I have saved an initial date as a JSON string, so you can click on "Load JSON Date" and it will parse the JSON string and store the values in the 2 input fields.
2) You can then select another date range, and click "Store JSON Data" and it will stringify the data.
3) Change the date
4) click "Load JSON Data" and it will reset the fields back to the data you stored.
http://jsfiddle.net/1xqbgshm/4/
The code does the following:
$("#store").click(function () {
var date1 = $("#input1").val();
var date2 = $("#input2").val();
var dateObject = {
"fromDate": date1,
"toDate": date2
};
jsonString = JSON.stringify(dateObject);
alert(jsonString);
});
$("#load").click(function () {
var javascriptObject = $.parseJSON(jsonString);
$("#input1").val(javascriptObject.fromDate);
$("#input2").val(javascriptObject.toDate);
});
Does this help?
Related
I tried to compare two days and return an alert, if the startdate is higher than the enddate. I don't know why, but if I choose 19.04.2016 as the startdate and 01.05.2016 as the enddate, I receive the alert.
var main = function() {
var date1 = "";
var date2 = "";
$('h1').click(function() {
$('h1').remove();
})
$('#date-start').datepicker({
dateFormat: "dd.mm.yy",
minDate: new Date(),
onSelect: function(date) {
var startdate = $('#date-start').datepicker('getDate');
$('#date-end').datepicker('option','minDate',startdate);
}
})
$('#date-end').datepicker({
dateFormat: "dd.mm.yy"
})
$('#btn').click(function() {
date1 = $('#date-start').val();
date2 = $('#date-end').val();
if (date1 > date2) {
alert("Beginn muss vor dem Ende liegen");
$('#date-start').css("border-color","red");
$('#date-end').css("border-color","red");
}
if (date1 == "") {
alert("Bitte alle Felder ausfüllen");
$('#date-start').css("border-color","red");
$('#date-end').css("border-color","red");
}
document.getElementById("compare-date-text1").innerHTML = date1;
document.getElementById("compare-date-text2").innerHTML = date2;
})
}
$(document).ready(main)
Can you figure out why?
Thanks :)
When you set date1 and date2 you get string, not Date.
For get Date from datepicker you can use:
var date1 = new Date($('#date-start').datepicker('getDate'));
var date2 = new Date($('#date-end').datepicker('getDate'));
Then you can compare:
if (date1 > date2 ){.........}
to get the dates from the datepicker you need to:-
date1 = $('#date-start').datepicker("getDate");
date2 = $('#date-end').datepicker("getDate");
you are getting them back as strings to compare instead of dates.
You are comparing the date strings. Therefore, the string "19.04.2016" is greater than "01.05.2016". If you format the strings in the Datepicker ISO 8601 format "yy-mm-dd", then the strings should compare correctly. The better way is to call getDate like the others have suggested.
I followed most of the code in:http://techbrij.com/month-range-picker-jquery-ui-datepicker.
But I want to change the date format, therefore I changed the monthformat in the following code:http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js.
The problem is the original function always setting "from" <"to" date is not working anymore after I made 2 changes mentioned as below:
**original one in jquery-ui.min.js **
monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],
monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
changed to following: and also change the source of file accordingly
monthNames:["01","02","03","04","05","06","07","08","09","10","11","12"],
monthNamesShort:["01","02","03","04","05","06","07","08","09","10","11","12"]
in html also change
Example:201410, then year=2014, month=10
year = datestr.substr(0,datestr.length-3);
month = datestr.substr(datestr.length-2,datestr.length-1);
you can see the complete code as below:
<script type="text/javascript">
$(function() {
$( "#from, #to" ).datepicker({
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'yyMM',
onClose: function(dateText, inst) {
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
$(this).datepicker('setDate', new Date(year, month, 1));
},
beforeShow : function(input, inst) {
if ((datestr = $(this).val()).length > 0) {
year = datestr.substr(0,datestr.length-3); //here changed
month = datestr.substr(datestr.length-2,datestr.length-1); //here changed
$(this).datepicker('option', 'defaultDate', new Date(year, month, 1));
$(this).datepicker('setDate', new Date(year, month, 1));
}
var other = this.id == "from" ? "#to" : "#from";
var option = this.id == "from" ? "maxDate" : "minDate";
if ((selectedDate = $(other).val()).length > 0) {
year = datestr.substr(0, selectedDate.length-3); //here changed
month = datestr.substr(selectedDate.length-2,selectedDate.length-1); //here changed
$(this).datepicker( "option", option, new Date(year, month, 1));
}
}
});
$("#btnShow").click(function(){
if ($("#from").val().length == 0 || $("#to").val().length == 0){
alert('All fields are required');
}
else{
alert('Selected Month Range :'+ $("#from").val() + ' to ' + $("#to").val());
}
})
Hope someone could help figure out the reason, thanks in advance.
Modified
year = datestr.substr(0,datestr.length-2);
month = datestr.substring(datestr.length-2);
Since the dateFormat is yyMM, datestr would return something like 201511. You are extracting
year = datestr.substring(0,3); // 201
Which is missing by one character. Use
year = datestr.substring(0,4); // 2015
I have two Jquery date pickers, in which a range of dates can be selected.
I have implemented certain restrictions like, the date of textbox2 should be always greater than textbox1. In addition I have disabled certain dates.
What I need is, if a user selects from date, and then selects to date, if there exist a disabled date in between, then the user should not be able to select that range.
For example:
I have disabled the dates: "31-5-2014", "1-6-2014", "2-6-2014"
If user selects date1 as 29-5-2014, and tries to select 4-6-2014 as the second date, then he should not be able to do that as disabled dates are in betweeb. The max value for date2 must be 30-5-2014
Adding the fiddle
I added a function "validateDateRange" to your code to illustrate the logic required to complete this task. Please note that the intention of the function I added is to simply pop up an alert if the condition you described occurs. From here you should be able to do whatever you like. Let us know if you have more questions or were looking for something else.
Here are my updates
function validateDateRange() {
var txtStartDate = $("#start_date");
var txtEndDate = $("#end_date");
var startDate;
var endDate;
var tempDate;
if (txtStartDate.val() == "")
return false;
if (txtEndDate.val() == "")
return false;
startDate = new Date(txtStartDate.val());
endDate = new Date(txtEndDate.val());
for (i = 0; i < unavailableDates.length; i++) {
var temp = unavailableDates[i].split("-");
tempDate = new Date(temp[2], temp[1]-1, temp[0]);
if (startDate < tempDate && endDate > tempDate) {
alert("Invalid Date Range");
return false;
}
}
}
Provided that The jQuery UI Datepicker doesn't support such functionality, manual way is the way ahead.
You can use onSelect option of date picker in start_date date Picker to achieve this functionality.
$('#start_date').datepicker(
{
beforeShow: customRangeStart,
beforeShowDay: unavailable,
minDate: 0,
dateFormat: "yy-mm-dd",
changeYear: true,
onSelect: function() {
//Do validation functionality here
triggerOnStartSelect();
}
});
And write down the validation functionality for setting the new maxDate of end_date date picker as :
//Trigger upon change event of either start or end date
function triggerOnStartSelect(){
var startDate = new Date($("#start_date").datepicker("getDate"));
var endDate = new Date($("#end_date").datepicker("getDate"));
//if required you could reset all of the default setting here //
//And can also validate the date objects
//Holds to be set maxdate of end_date datepicker
var tempEndDate= null ;
//unavailableDateObjects : Array of date objects listed as disabled
$.each(unavailableDateObjects, function(i, disabledRangeDate) {
if (startDate < disabledRangeDate) {
tempEndDate=new Date(disabledRangeDate);
//subtracts one day from the nearest disabled range date
tempEndDate.setDate(tempEndDate.getDate() - 1);
return false;
}
});
//Sets maxDate to the closest disabled date range or null . if null denotes no maxdate.
$( "#end_date" ).datepicker( "option", "maxDate", tempEndDate);
}
And you could obtain the date objects array from your string array list
var unavailableDates = ["31-5-2014", "1-6-2014", "2-6-2014", "3-6-2014"];
as (Or you could directly define date array object resembling the unavailableDates array ):
//Convert String Date List to Date object List
function convertDisabledFieldToDateObject(diabledList) {
var dateList = [];
$.each(diabledList, function (i, singleDate) {
var parsedDate = $.datepicker.parseDate("dd-mm-yy",singleDate);
dateList.push(parsedDate);
});
//Sort date if the diabled date sets are in jumbled order
dateList.sort(function(date1, date2){
return date1 - date2;
});
return dateList;
}
Which would be called after initialization of date string array.
Check out this Demo Fiddle
On course of solving this question, i found one interesting question that could be used for solving this problem(could be) :
JQuery Datepicker find next disabled date
var StartDate = $("#start_date").val();
var EndDates = $("#end_date").val();
var selectedDate = $("#selected_date").val();
//-- Start Date Convert in YMD
var Sdate = StartDate.split("-");
var Syear= Sdate[2];
var Smonth= Sdate[1];
var Sday= Sdate[0];
var SYMDDate = Syear + '-' + Smonth + '-' + Sday;
var newdate= new Date(SYMDDate);
var StartDateStrToTime=newdate.getTime();
//-- End Date Convert in YMD
var Edate = EndDates.split("-");
var Eyear= Edate[2];
var Emonth= Edate[1];
var Eday= Edate[0];
var EYMDDate = Eyear + '-' + Emonth + '-' + Eday;
var newdates= new Date(EYMDDate);
var EndDateStrToTime=newdates.getTime();
//-- Selected Date Convert in YMD
var Cdate = selectedDate.split("-");
var Cyear= Cdate[2];
var Cmonth= Cdate[1];
var Cday= Cdate[0];
var CYMDDate = Cyear + '-' + Cmonth + '-' + Cday;
var newdateses= new Date(CYMDDate);
var SelectedDateStrToTime=newdateses.getTime();
if((SelectedDateStrToTime>=StartDateStrToTime) && (SelectedDateStrToTime<=EndDateStrToTime))
{}
else
{
alert("Please Select date between "+StartDate+" to " +EndDates+".");
$("#selected_date").val(EndDates);
}
i am using Jquery-ui 1.7.2 calendar in my project. I have Jquery-ui-1.7.2.js and Jquery-ui-1.7.2.css for my calender.
When i select pickup and return date, both are shown in red color. But, I also want to highlight dates between these two in my calendar with my choice of color.
Please help me out with code.
Working Fiddle
Try this:
$(".datepicker").datepicker({
minDate: 0,
numberOfMonths: [12,1],
beforeShowDay: function(date) {
var date1 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#input1").val());
var date2 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#input2").val());
return [true, date1 && ((date.getTime() == date1.getTime()) || (date2 && date >= date1 && date <= date2)) ? "dp-highlight" : ""];
},
onSelect: function(dateText, inst) {
var date1 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#input1").val());
var date2 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#input2").val());
if (!date1 || date2) {
$("#input1").val(dateText);
$("#input2").val("");
$(this).datepicker();
} else {
$("#input2").val(dateText);
$(this).datepicker();
}
}
});
I have one datepicker with numberOfMonths set to 2.
Arrival Date and Departure Date are determined using this logic (within onSelect):
if ((count % 2)==0) {
depart = $("#datepicker-1").datepicker('getDate');
if (arriv > depart) { temp=arriv; arriv=depart; depart=temp; }
$("#check-in").val($.datepicker.formatDate("DD, MM d, yy",arriv));
$("#check-out").val($.datepicker.formatDate("DD, MM d, yy",depart));
} else {
arriv = $("#datepicker-1").datepicker('getDate');
depart = null;
if ((arriv > depart)&&(depart!=null)) { temp=arriv; arriv=depart; depart=temp; }
$("#day-count").val('');
$("#check-in").val($.datepicker.formatDate("DD, MM d, yy",arriv));
$("#check-out").val($.datepicker.formatDate("DD, MM d, yy",depart));
}
if(depart!=null) {
diffDays = Math.abs((arriv.getTime() - depart.getTime())/(oneDay));
if (diffDays == 0) { $("#day-count").val((diffDays+1)+' Night/s'); } else { $("#day-count").val(diffDays+' Night/s'); }
}
Getting the number of days within these 2 dates has no problem
What I want now is highlight those dates starting from the Arrival to Departure
I tried working around the onSelect but had no luck.
I am now using beforeShowDay to highlight these dates but I can't seem to figure it out
Got a sample from here
Basically, it is customized to highlight 11 or 12 days after the selected date (Here's the code from that link).
$('#datePicker').datepicker({beforeShowDay: function(date) {
if (selected != null && date.getTime() > selected.getTime() &&
(date.getTime() - selected.getTime())
Since I am new to using the UI, and the logic is not clear to me yet, I can't seem to figure this out. Any ideas on how I can make this highlight dates between the Arrival and Departure using my aforementioned logic used in determining the two?
Super old question but I came across the answer for anyone that finds this: http://jsfiddle.net/kVsbq/4/
JS
$(".datepicker").datepicker({
minDate: 0,
numberOfMonths: [12, 1],
beforeShowDay: function (date) {
var date1 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#input1").val());
var date2 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#input2").val());
return [true, date1 && ((date.getTime() == date1.getTime()) || (date2 && date >= date1 && date <= date2)) ? "dp-highlight" : ""];
},
onSelect: function (dateText, inst) {
var date1 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#input1").val());
var date2 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#input2").val());
if (!date1 || date2) {
$("#input1").val(dateText);
$("#input2").val("");
$(this).datepicker();
} else {
$("#input2").val(dateText);
$(this).datepicker();
}
}
});
IF this helps.. :-)
$(function() {
var togo=['10/25/2013']
var datesArray=['10/27/2013','10/28/2013']
var datesArray1=['10/25/2013','10/26/2013']
var datesArray2=['10/24/2013']
$( "#datepicker" ).datepicker({
numberOfMonths: 2,
selectMultiple:true,
beforeShowDay: function (date) {
var theday = (date.getMonth()+1) +'/'+
date.getDate()+ '/' +
date.getFullYear();
return [true,$.inArray(theday, datesArray2) >=0?"specialDate":($.inArray(theday, datesArray)>=0?"specialDate2":($.inArray(theday, datesArray1)>=0?"specialDate1":''))];
},
onSelect: function(date){
console.log("clicked"+date);
return [true,$.inArray(['10/24/2013'], togo) >=0?"specialDate":($.inArray(date, datesArray1)>=0?"specialDate1":'')] ;
}
});
//$.inArray(theday, datesArray) >=0?"specialDate":'specialDate1'
});
http://jsfiddle.net/pratik24/Kyt2w/3/
Not quite an answer, but this may be useful:
http://www.eyecon.ro/datepicker/
Rather unfortunately named, but it seems like it could be what you need.