Combining 2 jquery scripts to work together - javascript

I have these 2 scripts and the problem is that function check is called only if #hotel state is changed.
How can I make function check run and in the case of #hotel doesn't change.
var hotelMap = { hotel_a: 15, hotel_b: 5, hotel_c: 10 }; //Edw mporeis na allazeis to release period gia kathe ksenodoxeio
$(function() {
$('#hotel').change(function() {
var selectVal = $('#hotel :selected').val();
$("#from, #to").datepicker("option", "minDate", hotelMap[selectVal]);
});
var dates = $('#from, #to').datepicker({
defaultDate: "+1w",
changeMonth: true,
dateFormat: 'yy-m-d',
minDate: 15,//Episis edw prepei na mpainei to release period tou prwtou stoixeiou sth lista
numberOfMonths: 3,
onSelect: function(selectedDate) {
var option = this.id == "from" ? "minDate" : "maxDate";
var instance = $(this).data("datepicker");
var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
dates.not(this).datepicker("option", option, date);
}
});
});
$(document).ready(check);
function check(){
$('#from, #to, #hotel').bind('change', update);
$('#wait').show();
}
function update(){
var from=$('#from').attr('value');
var to=$('#to').attr('value');
var hotel=$('#hotel').attr('value');
$.get('get_availability.php', {from: from, to:to, hotel:hotel}, show);
}
function show(avail){
$('#wait').hide();
$('#availability').html(avail);
}

Move the functions in the second file out of the document ready (at the window level). At the moment they are only scoped to the document ready event.
Then you can call the functions from anywhere (although you may want to put them in a closure). It doesn't matter in which order the files are loaded as the functions are evaluated first.
For performance reasons its best to try put this code into one file though. If this is possible, then you can put the functions together with the code in one document.ready. This is probably the best solution.

You could use jQuery's trigger event. So somewhere in your code, you could add this:
$('#hotel').trigger('change');
Edit:
I updated your demo... I added a new trigger event called "update" inside the change function and inside the datepicker function. Then I changed your check() function to bind to the update and blur events (blur works better in the date picker window for some reason).
Here is the code I ended up with:
var hotelMap = { hotel_a: 15, hotel_b: 6, hotel_c: 10 };
$(function() {
$('#hotel').change(function() {
// assign the value to a variable, so you can test to see if it is working
var selectVal = $('#hotel :selected').val();
$("#from, #to").datepicker("option", "minDate", hotelMap[selectVal]);
$(this).trigger('update');
});
var dates = $('#from, #to').datepicker({
defaultDate: "+1w",
changeMonth: true,
dateFormat: 'yy-m-d',
minDate: 10,
numberOfMonths: 1,
onSelect: function(selectedDate) {
var option = this.id == "from" ? "minDate" : "maxDate";
var instance = $(this).data("datepicker");
var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
dates.not(this).datepicker("option", option, date);
$(this).trigger('update');
}
});
});
$(function(){
$('#from, #to, #hotel').bind('update blur', function(){
var from=$('#from').attr('value');
var to=$('#to').attr('value');
var hotel=$('#hotel').attr('value');
$('#availability').html(hotel + ' : ' + from + ' -> ' + to);
});
})

Related

Highlight whole week: Bootstrap Datepicker (No jquery ui)

I have this code, to highlight entire week if i click on dates
$(function () {
var $weekPicker = $("#calendar");
$weekPicker.datepicker({
calendarWeeks: true,
maxViewMode: 0,
weekStart: 1
}).on('changeDate', function (e) {
if ($weekPicker.data('updating') === true) {
return;
}
$weekPicker.data('updating', true);
var monday = moment(e.date).isoWeekday(1).startOf('week');
var weekDates = [
monday.clone().add().toDate(),
monday.clone().add(1, "days").toDate(),
monday.clone().add(2, "days").toDate(),
monday.clone().add(3, "days").toDate(),
monday.clone().add(4, "days").toDate(),
monday.clone().add(5, "days").toDate(),
monday.clone().add(6, "days").toDate()
];
$(this).datepicker('clearDate').datepicker('setDates', weekDates);
$weekPicker.data('updating', false);
});
});
however, i would like to make it instead of "change" to auto detect current date and highlight the whole week. This is my latest code and it doesnt work
$(function () {
//i need this for.. reasons
var selectedDate = calendar.datepicker('setDate', new Date());
//this is for calculation
var selectedDate2 = calendar.datepicker('getUTCDate');
if (selectedDate2&&selectedDate) {
var dateList = getDateList(selectedDate2);
getDatePeriodList(selectedDate2);
displayDates(dateList);
$("#addp").css("display", "block");
$("#info").css("display", "none");
//include code above so will highlight whole current week
}
});
Please guide me on this. Thanks :)
Add changeDate event listener with $('.day.active').closest('tr').find('.day').addClass('active');.
<div id="sandbox-container">
<div id="datepicker"></div>
<input type="hidden" id="my_hidden_input">
</div>
$(function() {
var date = new Date();
var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());
$('#datepicker').datepicker({
todayHighlight: true
});
$('#datepicker').datepicker('setDate', today);
activeWeek();
$('#datepicker').on('changeDate', function() {
$('#my_hidden_input').val($('#datepicker').datepicker('getFormattedDate'));
activeWeek();
});
function activeWeek() {
$('.day.active').closest('tr').find('.day').addClass('active');
}
})
example here

Allow datepicker to show only specific month

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.

Set minDate to a dynamical date in jQuery datapicker

The minimum date setting (minDate) in a jQuery-UI datepicker should be set to the birthdate (birthdateDMY in my code). I was thinking of using an anonymous function inside .datepicker({}) but I do not know how to make it work.
//birthdateDMY will be something like [ "01", "07", "2015" ]
var name = jQuery("#dropdown").val();
var index = baby.Name.indexOf(name);
var birthdateDMY = baby.BirthDate[index].split("/");
jQuery(function() {
jQuery("#datepicker").datepicker({
//need an anonymous function here to set minDate?
minDate: (new Date(birthdateDMY[2], birthdateDMY[1] - 1,
birthdateDMY[0])),
maxDate: 0,
dateFormat: "dd/mm/yy"
});
SOLVED USING A SETTER:
//Setter: update minDate for e.g. #datepicker
function updateMinDate(selector){
//birthdateDMY will be something like [ "01", "07", "2015" ]
var name = jQuery("#dropdown").val();
var index = baby.Name.indexOf(name);
var birthdateDMY = baby.BirthDate[index].split("/");
//Update minDate in the selected item
$(selector).datepicker("option", "minDate", new Date(birthdateDMY[2], birthdateDMY[1] - 1, birthdateDMY[0]) );
}
//When changin #dropdown, call updateMinDate
jQuery(document).on('change', '#dropdown', function(e) {
updateMinDate("#datepicker");
}
jQuery(function() {
jQuery("#datepicker").datepicker({
minDate: <some code run when page loads>,
maxDate: 0, numberOfMonths: 2, dateFormat: "dd/mm/yy"
});
});
You need to reinitialize your datepicker whenever your drop down changes. Right now when your page loads it sets up the datepicker and then it never changes it.
So, an event like this should help:
$("#dropdown").change(function(){
//reinitialize date-picker here
});
You might have to play around with it a little but I think this will solve your problem.

JQuery datepicker, months year only on input

I have a question, quite similar to the one at: year/month only datepicker inline
The difference is that I am using the input version, rather than the div.
In the div case, the ui-datepicker-calendar is inside the outer div, and so can be accessed uniquely.
But with the input, there is no relation between the input and the ui-datepicker-calendar (or, not that I've found...)
Just to be clear, I cannot use the "global" .ui-datepicker-calendar { display: none;}, as I have other datepicker that is a full one (i.e., uses the days as well).
My code looks as follows:
$("#monthsYearInput").datepicker({
changeMonth: true,
changeYear: true,
dateFormat: "mm/yy",
onClose: function(dateText) {
if (dateText != "") {
var selectedDate = $.datepicker.parseDate("dd/mm/yy", "01/" + dateText);
$(this).datepicker("setDate", selectedDate);
$(this).datepicker("refresh");
}
},
beforeShow: function() {
var dateText = $(this).val();
var isPopulated = dateText.length > 0;
if (isPopulated) {
var selectedDate = $.datepicker.parseDate("dd/mm/yy", "01/" + dateText);
$(this).datepicker("option", "defaultDate", selectedDate);
$(this).datepicker("setDate", selectedDate);
$(this).datepicker("refresh");
}
},
onChangeMonthYear: function(year, month) {
if (changingDate) {
return;
}
changingDate = true;
$(this).datepicker("setDate", new Date(year, month - 1, 1));
$(this).datepicker("refresh");
changingDate = false;
}
});
$("#monthsYearInput").focus(function () {
$(".ui-datepicker-calendar").hide();
};
$("#monthsYearInput").blur(function () {
$(".ui-datepicker-calendar").hide();
};
It all looks OK as start, but then when the year/month has changed, the new date is populated in the input (desired), but now the calendar displays (not desired).
Any ideas on how to solve this issue?...
Thanks in advance.
JSfiddle: http://jsfiddle.net/OhadRaz/8z9M2/
I think that you could still do it with a css like in the solution that you've linked but targeting only that one datepicker
#monthsYearInput .ui-datepicker-calendar { display: none;}
Can you put your code on JSFiddle so we can see what it is doing? I may have done something familiar at Jquery Datepicket Supress Year, but can't tell without a JSFiddle demo...
OK,
I came up with some sort of a solution:
var superUpdateDatepicker = $.datepicker._updateDatepicker;
$.datepicker._updateDatepicker = function(inst) {
var ret = superUpdateDatepicker.apply(this, arguments);
if (inst.id == "monthsYearInput") {
$(".ui-datepicker-calendar").hide();
}
return ret;
}
While working, I am not happy with it.
It is too hacky, it is not clean, and I just don't like it.
Any better ideas?...

Using jQuery to create two datepicker date-range instances

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);
}
});

Categories