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();
Related
I would like to add a datepicker to filter data in a Datatable.
I saw many example where the datepicker is used with a range of dates, but I would like that the Datatable shows only the data which contain the date selected in the datepicker.
I've tried to do it here: https://jsfiddle.net/c9q5b0k3/3/
The javascript code I've wrote is:
$(document).ready(function() {
$('.datepicker').datepicker({
format: "yyyy/mm/dd"
});
});
$.fn.dataTable.ext.search.push(
function(settings, data, dataIndex) {
var dateSelected = $('#date').val();
var date = data[4];
if (dateSelected === "") {
return true;
}
if (date === dateSelected) {
return true;
}
return false;
}
);
$(document).ready(function() {
var table = $('#sspTable').DataTable({
responsive: true
});
$('#date').keyup(function() {
table.draw();
});
});
But the problem that it only works if I select a date in the datepicker and then I click the arrows in the Datatables(the ones that order the data) or if I press multiple times Enter.
What is the problem? Is it possible otherwise to add the datepicker to the search bar of the Datatable?
Thanks in advance!
You need to call table.draw() when a value is selected in the datepicker. To do that you can amend the existing keyup event handler you have to also include change, like this:
$('#date').on('keyup change', function() {
table.draw();
});
Updated fiddle
I'm developing a Calendar application via fullcalendar.
I'm currently working on a mini sized calendar. The mini calendar will not display the events.
I'm trying to use tooltip instead. so when the user will mouseover a specific daycell - all the events of the specific daycell will be displayed via tooltip. (this is my issue)
I been working on this issue for almost two days now.
unfortunately, full calendar only offers "eventMouseover". (no dayMouseover available).
Also, using $(".fc-day").hover is not really the best way to go because it is working only when hovering the bottom of the cell.
there is no documentation for this on the web so far.
Anybody knows which is the best way to Tackle an issue?
here is my code so far:
$("#miniCalendar").fullCalendar({
defaultDate: currentDate,
viewRender: function (view, element)
{
monthStart = view.intervalStart.format("YYYY-MM-DD");
monthEnd = view.intervalEnd.subtract(1, "days");
monthEnd = view.intervalEnd.format("YYYY-MM-DD");
mStart = view.intervalStart.format("M");
yStart = view.intervalStart.format("YYYY");
},
events: function (start, end, timezone, callback) { //custom events function to be called every time the view changes
$.ajax({
url: getMonthDataUrl,
type: "post",
data: {
startDate: monthStart,
endDate: monthEnd,
custom_config: Config
},
error: function () {
//alert("there was an error while fetching events!");
},
success: function (data) {
calendarData = data;
console.log(calendarData);
thingsToDoAfterWeLoadCalendarData(calendarData);
callback(eventsJsonArray); //pass the event data to fullCalendar via the supplied callback function
}
});
},
fixedWeekCount: false,
dayRender:
function (date, cell) {
//the events are loaded vie eventAfterAllRender function
//eventAfterAllRender takes time to load. so we need dayRender function in order to give the calendar default colors until the real colors are loaded
// the default colors spouse to look like the correct colors. this is needed for a better looking calendar while loading new events
if (!cell.hasClass("fc-other-month")) {
//that means this is a cell of this current month (becuase only cells that belong to other month have the "fc-other-month" class
var weekDay = date.format("dddd");
if (weekDay == "Saturday" || weekDay == "Friday") {
cell.css("background-color", "#edf5f9");
} else{
//regular days
cell.css("background-color", "#f7fafc");
}
} else{
//cells that belong to the other months
$(".fc-other-month").css("background-color", "#ffffff");
}
},
eventAfterAllRender:
(function(view, event, element) {
let viewDisplay = $("#miniCalendar").fullCalendar("getView");
if (viewDisplay.name == "month") { //checking if this the month view. this is needed for better display of the week\day view (if we ever want to use it)
$(".fc-day:not(.fc-other-month)").each(function(index, element) {
//loop through each current month day cell
$(this).empty(); //removing old icons in case they are displayed
let cellDate = moment($(this).data("date")).format("YYYY-M-D"); // "YYYY-M-D" date format is the key in the json_backgrundColorBigCalendar array
$(this).css("background-color", json_backgrundColorBigCalendar[cellDate]); //set the background colour of the cell from the json_backgrundColorBigCalendar array.
});
}
$(".fc-other-month").css("background-color", "#ffffff"); //days that belong to other month gets a color background that will show this days are irrelevant
}),
dayClick: function(date, jsEvent, view) {
window.location = fullCalendarUrl;
},
});
I dont really know if there is a "fullcalendar-way" doing this, but why can't you use your hover event listener and just also let it listen on fc-day-top hover?
$(".fc-day, .fc-day-top").hover(function(e) {
console.log($(e.currentTarget).data("date"));
});
This will also work if you hover the top of a day cell.
Update:
To get the events on hover use this:
var $calendar = $("#calendar");
$(".fc-day, .fc-day-top").hover(function(e) {
var date = moment.utc($(e.currentTarget).data("date"));
var events = $calendar.fullCalendar("clientEvents", function(event) { return event.start.startOf("day").isSame(date); });
console.log(events);
});
(Tested on the calendar on the fullcalendar main site).
Of course you have to change the jQuery selector of the calendar (#calendar) as it is in your code.
I've never seen full calendar before, but if I understand correctly you want to bind a hover function to custom days of the calendar. Is that correct?
If so you can simply select days of the calendar with their "data-date" attribute. So something like the code below would let you specify a hover function for a desired day:
$("[data-date='2017-10-10']").hover(function(e) {
console.log("You moused over 10/10/2017!");
});
I am trying to update my db with the updated start date of an event I drag to a new day. I have a save button that runs the 'clientEvents' method to return all events to insert/update to the db. My problem is returning the correct event start date when an event that has been dragged to a new day.
I am doing this so far to update the event data:
$('#calendar').fullCalendar({
eventDrop: function(event, delta, element) {
event.title = "NEW TITLE!";
event.start = event.start.format();
event.color = "blue";
console.log(event.start.format());
console.log(event.start);
console.log(event.start._i);
console.log(event.title);
console.log(event.color);
$('#calendar').fullCalendar('updateEvent', event); //update the event data
}
})
and my function to return all the events:
function saveEvents() {
//get events array
var events = $('#calendar').fullCalendar('clientEvents');
console.log(events);
}
However, using this code, the title and color update fine but the start date will not update. Using console.log, the new title and color return correctly, but the start date is the original date, not the new date the event was dragged to. The same for the event data returned in my saveEvents function: the new title and color are correct, but not the start date.
The strange thing is, in the 3 ways I log the event.start, only the event.start.format() shows the correct new date. How do I get the new date saved so when a call 'clientEvents', the correct new data is returned?
Could you explain what you mean by "original date" compared to what should be the "new date" ? Because you don't seem to update your start date as you only modify its format.
Create a moment copy of start, format it and attach to new event. Put your ajax call in the eventDrop callback in initialization of fullCalendar. Example solution using php and mysql:
$('#calendar').fullCalendar({
eventDrop: function(event, delta, element) {
var event_format = event;
event_format.start = moment(event.start).format();
$.ajax({
url : "script.php",
data : event=JSON.stringify(event_format),
type : "POST"
});
}
})
php:
<?php
$event = json_decode($_POST['event']);
$query = "UPDATE x SET start = '$event->start'";
mysql_query($query) or die ($query);
?>
Doing the same for the enddate would be a good idea :)
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
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;
}
}
}