How can I add 4 hours from my date-time pickers' startDate to endDate?
$(function() {
$('#startDate').datetimepicker();
$('#endDate').datetimepicker();
$("#startDate").on("dp.change", function(e) {
$('#endDate').data("DateTimePicker").setMinDate(e.date);
});
$("#endDate").on("dp.change", function(e) {
$('#startDate').data("DateTimePicker").setMaxDate(e.date);
});
});
Your e.date objects are instances of Moment. As you can see in the documentation, you can use the .add and .subtract functions on them:
$('#endDate').data("DateTimePicker").setMinDate(e.date.add(4, 'hours'));
// ...
$('#startDate').data("DateTimePicker").setMaxDate(e.date.subtract(4, 'hours'));
As for the comments:
To set the default date, use the defaultDate option. It works with both Moments and native Dates:
$('#startDate').datetimepicker({ defaultDate: Date() });
$('#endDate').datetimepicker({
defaultDate: $('#startDate').data("DateTimePicker").date().add(4, 'hours')
});
Also get rid of the dp.change event handlers, you don't need those callbacks just to set the default date. Unless of course you want to keep them linked, then use the dp.change but use the date function instead of the setMinDate and setMaxDate:
$("#startDate").on("dp.change", function(e) {
$('#endDate').data("DateTimePicker").date(e.date.add(4, 'hours'));
});
Beware an infinite loop if you want to link them like that both ways, calling date with a different date will trigger a new dp.change. While that shouldn't happen in your setup, it may start to if you tweak it slightly.
Have you tried this:
To add minutes:
$('#Start').data("DateTimePicker").date(e.date.add(30, 'minutes'));
To add hours:
$('#Start').data("DateTimePicker").date(e.date.add(4, 'hours'));
Also with below script, you can compare start and end date, and if they were equal or start date time was after end date time, you set your default date time again based on new selected date time by user, I always set the default date time on server side:
//Server side default setup for first run
Start = DateTime.Now;
End = DateTime.Now.AddMinutes(30);
And here is the js script:
<script type='text/javascript'>
$(function()
{
$('#Start').datetimepicker({
useCurrent: false //Important! See issue #1075
});
$('#End').datetimepicker({
useCurrent: false //Important! See issue #1075
});
$('#Start').on("dp.change",
function(e)
{
if (dateSorter($('#End').val(), $(this).val()) === -1 || dateSorter($('#End').val(), $(this).val()) === 0)
// if ($('#End').val() < $(this).val())
{
// console.log("End date "+$('#End').val()+ " is before start date: "+ $(this).val());
$('#End').data("DateTimePicker").date(e.date.add(30, 'minutes'));
}
// add your other scripts for example update something on the page, updateAvailableSeats();
});
$('#End').on("dp.change",
function(e)
{
if (dateSorter($('#Start').val(), $(this).val()) === 1 || dateSorter($('#Start').val(), $(this).val()) === 0)
// if ($('#Start').val() > $(this).val())
{
// console.log("Start date " + $('#Start').val() + " is after end date: " + $(this).val());
$(this).data("DateTimePicker").date(e.date.add(30, 'minutes'));
}
});
// updateAvailableSeats();
});
Hope this helps.
Thanks
Related
I am trying to have an event triggered when you click on the start date in the date range picker, I have tried a few ways and have this so far:
HTML:
<input class="form-control pull-right" type="text" name="daterange" id="dateRangeP" >
Javascript
$(function () {
$('input[name="daterange"]').daterangepicker({
locale: {
format: 'DD-MM-YYYY'
}
});
$('input[name="daterange"]').click(function () {
debugger;
var startDate = $("#dateRangeP").data('daterangepicker').startDate._d.toLocaleDateString('en-GB');
var endDate = moment(startDate, "DD-MM-YYYY").add(7, 'days')._d.toLocaleDateString('en-GB');
$("#dateRangeP").data('daterangepicker').setStartDate(startDate);
$("#dateRangeP").data('daterangepicker').setEndDate(endDate);
debugger;
$(this).val(startDate + '-' + endDate);
console.log($(this).val());
});
});
At the moment it works when you click outside the box but I need it for when I click on the start date. I have tried to use change the function to call below but it only works after the apply button is selected and both dates have been selected
$('#dateRangeP').on('apply.daterangepicker', function(ev, picker) {
alert ('hello');
});
I have done a lot of searching before posting here but cannot seem to find any guidance, some guidance would be greatly appreciated. If unclear please let me know.
Fiddle: http://jsfiddle.net/40cwdk7h/1/
Try this ...
dateLimit: { days: 7 }
$(function() {
$('input[name="daterange"]').daterangepicker({
dateLimit: { days: 7 },
locale: {
format: 'MM/DD/YYYY '
},
});
});
link https://jsfiddle.net/rLnycn80/1845/
Yes, that function is only called when you clicked on apply button.
For setting a dynamic end date at runtime used two datepicker instead of daterangepicker.
Fiddle Link: https://jsfiddle.net/kartik_bhalala/2euar7d3/19/
I need to be able to set a "date range" with FullCalendar, using the "List" view. By date range, I mean being able to enter using 2 text fields, 2 different dates, for example :
Text field 1 : 2018-05-05
to
Text field 2 : 2018-05-06
And to filter the content of the calendar, using the List view to display the result, and show events that matches that date range.
Here's my code for the FullCalendar part:
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'listMonth, month,agendaWeek,agendaDay'
},
defaultView: 'listMonth',
locale: 'fr',
contentHeight: 600,
navLinks: true, // can click day/week names to navigate views
selectable: false,
eventRender: function(event, element, view) {
element.find('.fc-widget-header').append("<div style='color:#fff'>Conférencier choisi</div>");
element.find('.fc-title').append("<br/>" + event.lieu);
element.find('.fc-list-item-title').append("<br/>" + event.lieu);
element.find('.fc-list-item-title').append("<a href='" + event.lienconferencier + "'><div class='conferencier-calendrier-container'><div style='float:left;background-image:url(" + event.photoconferencier + ");width:40px;height:40px;background-size:cover;border-radius:100px;'></div><div style='float:left;padding-left:5px;font-weight:normal;'><strong>Conférencier</strong><br>" + event.conferencier + "</div></a>");
return ['all', event.status].indexOf($('#filter-status').val()) >= 0 &&
['all', event.client].indexOf($('#filter-contact').val()) >= 0 &&
['all', event.conferencier].indexOf($('#filter-conferencier').val()) >= 0 &&
['', event.numero].indexOf($('#numero').val()) >= 0;
},
selectHelper: true,
editable: false,
eventLimit: true, // allow "more" link when too many events
events: [
{
title: 'Example',
start: '2018-05-05',
end: '2018-05-06',
color: '#ff0000',
lieu: 'Montreal',
numero: '300445',
conferencier: 'John Doe',
photoconferencier: 'http://www.example.com/img/profile.jpg',
lienconferencier: 'http://www.example.com/profile/link.html',
url: 'http://www.google.com'
},
{
title: 'Example2',
start: '2018-05-08',
end: '2018-05-010',
color: '#ff0000',
lieu: 'New York',
numero: '300446',
conferencier: 'Steve Jobs',
photoconferencier: 'http://www.example.com/img/profile2.jpg',
lienconferencier: 'http://www.example.com/profile/link2.html',
url: 'http://www.apple.com'
},
],
});
And here's my text fields code:
<input type="text" placeholder="Date : From" id="start_date">
<input type="text" placeholder="Date : To" id="end_date">
I think I would have to add something like this:
$('#start_date').on('change', function () {
$('#calendar').fullCalendar('rerenderEvents');
});
$('#end_date').on('change', function () {
$('#calendar').fullCalendar('rerenderEvents');
});
But I am not sure. Also, please keep in mind that there's other filters too. Hence the "eventRender" part in the code with a bunch of stuff. So I need to make sure that "dateRange" filter won't break the other filters.
I read about "visibleRange" on FullCalendar's website, but I do not understand how I can make it work based on what is entered in the 2 "date range" text fields. I think also disabling the other views that I have set (to show the result in the List view only), would be a good idea.
Any idea how I can make it work? I'm kind of lost here.
Thanks a lot
EDIT :
I have tried this code:
$('#start_date').on('change', function () {
$('#calendar').fullCalendar('changeView', 'list', {
start: 2018-05-10,
end: 2018-05-30
});
});
Which is working. Basically, what it does is that I enter a new date in a text field with the ID of "start_date" (which uses a datepicker script, to that's why I went with "on change"), it changes the view to the list view, which is great, and displays only the events between the date I have entered. So to make it dynamic, I did this :
$('#start_date').on('change', function () {
var start_date = $('#start_date').val();
var end_date = $('#end_date').val();
$('#calendar').fullCalendar('changeView', 'list', {
start: start_date,
end: end_date
});
});
I have 2 fields, "start_date", and "end_date".
I thought that setting the "start" and "end" option in the changeView code for FullCalendar would update automatically everytime I select a new date, but it doesn't work. In fact, it works partially. If I enter the "end_date" first, then the "start_date", it will filter and work perfectly, showing the right date range. But after that, I cannot change it for another dateRange by changing the dates in the fields.
It acts like this probably because my function is "on change", based on the "#start_date" element. So I have to select the end_date first, to make sure it filters and change the view with something in the "end" option.
Any idea what I am doing wrong?
Thanks
EDIT 2 :
I tried changing the function from a "change" event to "click", and adding a "search" button. There's 2 issues here.
1 - It works only once. If I make a search, then change the date, and click again on the "#search-range" button, it won't do anything.
2 - When it works (first time after page load), if I select from May 1rst to May 5th for example, it will show the range from May 1rst to May 4th, for some reasons. Here's my code again :
$('#search-range').on('click', function () {
var start_date = $('#start_date').val();
var end_date = $('#end_date').val();
$('#calendar').fullCalendar('changeView', 'list', {
start: start_date,
end: end_date
});
});
Any ideas what's going on?
Thanks again
You're probably looking for the validRange option.
$('#start_date').on('change', function(){
$('#calendar').fullCalendar('option', 'validRange', {
// Don't worry if user didn't provide *any* inputs.
start: this.value,
end: $('#end_date').val()
});
});
$('#end_date').on('change', function(){
$('#calendar').fullCalendar('option', 'validRange', {
// Don't worry if user didn't provide *any* inputs.
start: $('#start_date').val(),
end: this.value
});
});
Demo: https://jsfiddle.net/8wd7sxyv/
UPDATE
The end date is now inclusive. So if end date is 2018-05-31, events on that day are included — the default behavior only includes up to 2018-05-30.
If the start and end dates are in same month, view is listMonth; otherwise, it is listYear.
function filterByDateRange(start_date, end_date, format) {
var s = $.fullCalendar.moment(start_date),
e = $.fullCalendar.moment(end_date),
v = $('#calendar').fullCalendar('getView'),
a, b;
// Start date is invalid; set it to the start of the month.
if (! s.isValid()) {
b = e.isValid();
s = b ? e.clone() : $.fullCalendar.moment();
s.date(1);
$('#start_date').val(s.format(format));
a = true;
}
// End date is invalid; set it to the end of the month.
if (! e.isValid()) {
b = s.isValid();
e = b ? s.clone() : $.fullCalendar.moment();
e.date(e.daysInMonth());
$('#end_date').val(e.format(format));
a = true;
}
// Start date is after end date; set it to a day before the end date.
if (s.isAfter(e)) {
s = e.clone().add('-1', 'day');
$('#start_date').val(s.format(format));
// End date is before start date; set it to a day after the start date.
} else if (e.isBefore(s)) {
e = s.clone().add('1', 'day');
$('#end_date').val(e.format(format));
}
// Add 1 day so that `end_date` is inclusive.
e = e.isValid() ? e.add('1', 'day') : e;
$('#calendar').fullCalendar('option', 'validRange', {
start: s.isValid() ? s : null,
end: e.isValid() ? e : null
});
a = a || s.isSame(e, 'month');
// If months are different, switch to the year list.
if ('listYear' !== v.name && ! a) {
$('#calendar').fullCalendar('changeView', 'listYear');
// Otherwise, switch back to month list, if needed.
} else if ('listMonth' !== v.name) {
$('#calendar').fullCalendar('changeView', 'listMonth');
}
}
$('#start_date').on('change', function(){
filterByDateRange(this.value, $('#end_date').val(), 'YYYY-MM-DD');
});
$('#end_date').on('change', function(){
filterByDateRange($('#start_date').val(), this.value, 'YYYY-MM-DD');
});
Demo: https://jsfiddle.net/8wd7sxyv/6/
I have from and to input fields with bootstrap date picker. When query params not empty I would like to change the value of these input fields and trigger the change date event on datepicker because I have a function that calculates total price between dates. When user selects dates from datepicker works fine but if I change the value by jquery it does not calculate.
$('#from').val('<%= #from_date %>').trigger( 'change' );
$('#to').val('<%= #to_date %>').trigger( 'change' );
//function
var dates_avail = new DatesAvailability({
start: '#from',
end: '#to'
});
..
W.DatesAvailability = function (opts) {
var options = $.extend({}, defaultOpts, opts);
var start = options.start + ',' + options.rel_start;
var end = options.end + ',' + options.rel_end;
$(start + ',' + end).datepicker({
autoclose: true,
format: "yyyy-mm-dd",
startDate: '+1d',
endDate: '+3y',
..
}).
on('changeDate', function (e) {
// I would like to trigger this.
..
I also have these lines in bootstrap-datepicker.js
..
if (fromArgs){
// setting date by clicking
this.setValue();
this.element.change();
}
else if (this.dates.length){
// setting date by typing
if (String(oldDates) !== String(this.dates) && fromArgs) {
this._trigger('changeDate');
this.element.change();
}
}
..
Try using the update mention in the documentation. Something like `$(start + ',' + end).datepicker('update', qParamStart);
If you're trying to figure out how to get the query params this is a good reference.
You can do this by manually calling the event changeDate.
E.g.
$('.datepicker').datepicker().trigger('changeDate');
I would do something like this.
$('.datepicker').datepicker('_trigger', 'changeDate');
This uses an undocumented private method, but will fire with event and the extra data you would expect.
Inspect the link from the calendar then call it conventionally. For me it was:
$('.ui-state-active').click();
or
$('.ui-datepicker-current-day').click();
I have 2 datepickers on my webpage: One for the arrival date and the other for departure.
Now I'd like to set the min and max dates, according to the user selection.
2 Examples of what I want to achieve:
User selects 29.03.2015 as arrival -> departure's min date is set
accordingly.
User selects 29.03.2015 as departure -> arrival's max
date is set accordingly.
At the moment I am initializing the datepickers like so:
var startDate = "<?php echo date('d.m.Y'); ?>"; // Today
$('#startDate.input-group.date').datepicker({
format: "dd.mm.yyyy",
language: "de",
multidate: false,
todayHighlight: true,
startDate: startDate,
weekStart: 1
}).on('changeDate', function(e){
changeDate(e);
});
$('#endDate.input-group.date').datepicker({
format: "dd.mm.yyyy",
language: "de",
multidate: false,
todayHighlight: true,
startDate: startDate,
weekStart: 1
});
You notice the .on() function on the first datepicker. This is my current attempt to set the date of the 2nd one:
function changeDate(e){
$('#endDate.input-group.date').datepicker('setStartDate', e);
}
However this leaves me with the following error:
Uncaught TypeError: undefined is not a function: bootstrap-datepicker.js:1493
The line in question is this:
parts = date.match(/([\-+]\d+)([dmwy])/g)
Can you please give me a hint on what I am doing wrong and on how I can achieve said effect?
if you console.log changing like this:
.on('changeDate', function(e){
console.log(e);
});
you'll see the event returns an event object;
you should try passing something like e.date (but be sure to format the string accordingly to your startDate format).
Here's more about the extra data attached to the event object : http://bootstrap-datepicker.readthedocs.org/en/latest/events.html
Hi I have been trying to just get the date of a bootstrap date picker and have been able to but it seems to fires 3 times. NOTE: This is not jquery date picker but bootstrap date picker.
Using this date picker: https://github.com/eternicode/bootstrap-datepicker, not older eyecon.ro one.
$(".date-picker").on("change", function(e) {
contents = $(this).val();
id = $(this).attr('id');
console.log("onchange contents: " + contents);
console.log("onchange id: " + id);
});
HTML:
<input id="start_date" type="text" data-date-format="yyyy-mm-dd" class="date-picker form-control" />
I have used a few other options other than change, like
$('.date-picker').datepicker().change(function(){};
But this does not close date picker, hoping there is an easy solution to this. thx
You should be using the "changeDate" event. For example:
var datePicker = $('.date-picker').datePicker().on('changeDate', function(ev) {
//Functionality to be called whenever the date is changed
});
Please view the documentation here for more info on this event.
it does not fix the problem, but i was using the datepicker to send through an ajax post, so the 3 change events was causing me problems - the 3rd event always failed. even if the documentation says to use a changeDate event, it doesn't seem right to me to fire the input tag's change event 3 times. the value isn't changing 3 times!
I wrote a simple 'debounce' function to get around the problem. doesn't fix the issue - which is due to multiple change events being fired from the methods: setValue (line 508) _setDate:(line 1048) and setValue (line 508) (version 1.3.0) of the widget.
var lastJQueryTS = 0 ;// this is a global variable.
....
// in the change event handler...
var send = true;
if (typeof(event) == 'object'){
if (event.timeStamp - lastJQueryTS < 300){
send = false;
}
lastJQueryTS = event.timeStamp;
}
if (send){
post_values(this);
}
it is pretty simple, just finds the jquery 'event', and makes sure that values in a window of 300ms are ignored. in my testing this all happened in 30 msec or so.
As some has mentioned already, use this:
$('#calendar').on("changeDate", function() {
});
The trick is to use changeDate instead of change.
It seems as if when checking the change event, if the change was from actual user interaction, the change event contains a value for originalEvent.
The event does NOT contain this value if the input was changed via JS:
$obj.val('1990-03-07').change() and the same with bootstrap-datepicker
Here's how I set it up:
Generic initial setup
// General selector for date inputs
var $obj = $('input[type="date"]');
$obj.datepicker({
// options here, not important for this example
});
Handle bootstrap-datepicker specific changes
$obj.datepicker().on('changeDate', function (event) {
handleInputDateAndTimeChange(event);
});
Now, deal with user interaction changes
$('input[type="date"], input[type="time"]').change(function (event) {
// This checks if change was initiated by user input and NOT JS
if(event.originalEvent !== undefined) {
handleInputDateAndTimeChange(event);
}
});
And finally, here's the handleInputDateAndTimeChange function
function handleInputDateAndTimeChange(event) {
var $input = $(event.target);
// Do what you want with $input object here...
}
I tried the answer from #pgee70 and it doesn't work for me. So this is my solution, hope its help
var send=true;
$('.input-group.date').datepicker({
todayBtn: "linked",
keyboardNavigation: false,
forceParse: false,
language: 'es-ES',
weekStart: 1,
format: 'dd/mm/yyyy',
enableOnReadonly:false,
calendarWeeks: true,
autoclose: true,
todayHighlight:true
}).on("changeDate", function(e) {
if(send){
modificarFechaAplicacionCliente($("#input_filtro_fecha_cliente").val());
send=false;
}
setTimeout(function(){send=true;},200);
});
It´s not a beaty solution, but it´s work.
Similar to the above answer, but you should use datepicker unless you've renamed the function:
var datePicker = $('.date-picker').datepicker().on('changeDate', function(ev) {
//Functionality to be called whenever the date is changed
});
This works for me, except in my case, I renamed the function to datepickerBootstrap to avoid the clash with JQuery's. So then it would become:
var datePicker = $('.date-picker').datepickerBootstrap().on('changeDate', function(ev) {
// On change functionality
});
It is fixed find your fixed js datepicker file HERE
Read fixing description HERE
I have faced the same problem with bootstrap-datepicker when it used with the jQuery OnChange event they call function 3 times. Here is my code
#Html.TextBoxFor(x => x.CmpStartDate, "{0:dd-MMM-yyyy}", new { #size = "30", #class = "form-control search-date", #placeholder = "Start date" })
#Html.TextBoxFor(x => x.CmpEndDate, "{0:dd-MMM-yyyy}", new { #size = "30", #class = "form-control search-date", #placeholder = "End date" })
<script>
$('#CmpStartDate,#CmpEndDate').datepicker({
autoclose: true,
todayHighlight: true,
minViewMode: 3,
format: "dd-M-yyyy"
});
$(".search-date").on("change", function () {
cmpStartDate = $("#CmpStartDate").val();
cmpEndDate = $("#CmpEndDate").val();
SearchThisDateRecords(cmpStartDate,cmpEndDate);
});
function SearchThisDateRecords(cmpStartDate,cmpEndDate) {
console.log("Call search method");
}
</script>
We need to call this function only one time, Not multiple time so you can use the below logic to fix this problem
<script>
$('#CmpStartDate,#CmpEndDate').datepicker({
autoclose: true,
todayHighlight: true,
minViewMode: 3,
format: "dd-M-yyyy"
});
var i = 0;
$(".search-date").on("change", function () {
cmpStartDate = $("#CmpStartDate").val();
cmpEndDate = $("#CmpEndDate").val();
SearchThisDateRecords(cmpStartDate,cmpEndDate);
i++;
console.log(i);
if (i == 3) {
SearchThisDateRecords(cmpStartDate,cmpEndDate);
}
});
function SearchThisDateRecords(cmpStartDate,cmpEndDate) {
i =0; //Reset i value
console.log("Call search method");
}
</script>
Get global variable count and check if equal to 0 then execute Your function.
var count=0;
$( "#Id" ).datepicker({ minDate: 0}).on('change',function (){
if(count==0)
validity();//any function
count=1;
});
validity(){ count=0;}
bit annoying..
my code was:
var c=0;var send=false;
$(document).ready(function() {
jQuery( ".ed" ).datepicker({
format: "yyyy-mm-dd",
autoclose:!0
}).on('change',function() {
if(c==2){
c=0;
send=true;
}else{
c++;
send=false;
}
});
});
Please use changeDate function in place of change .
var LastController =['id','value']; //global variable...
function datepeakerchange(e){
if ((LastController[0] != e.target.id && LastController[1] != e.target.value) || (LastController[0] == e.target.id && LastController[1] != e.target.value)) {
LastController[0] = e.target.id;
LastController[1] = e.target.value;
write your code....
}
}
var pickerFireCount = 0;
function checkSelectedDateIsHollyday(rId) {
pickerFireCount++;
if (pickerFireCount == 3) {
if (!selectedDateIsHolyday(rId)) {
showInfoMessage('The date you selected is a holiday.');
pickerFireCount = 0;
}
}
}