apply.daterangepicker event stops firing when daterangepicker() constructor re-attached - javascript

I am using daterangepicker version: 3.0.3
I have a radio button pair that lets the user switch between local and utc time. When I click on the radio button I want to remove and re-attach the daterangepicker constructor so I can specify different pre-defined date ranges.
However, after clicking on the radio button the daterangepicker stops firing an event when I click "Apply" or click on a pre-defined date range.
I made a simplified version of my program on jsfiddle and the apply event is still not firing
https://jsfiddle.net/flexmcmurphy/re62qhb8/4/
Here is the code:
<html>
<head>
<title>Test2.html</title>
<script src="include/jquery-3.3.1.js"></script>
<script src="include/moment.js"></script>
<script src="include/daterangepicker.js"></script>
<link rel="stylesheet" type="text/css" href="include/daterangepicker.css" />
</head>
<body>
<input type="text" name="datetimes"/>
Local <input type="radio" name="timeformat" value="local" checked="checked"><span id="mybar">|</span><input type="radio" name="timeformat" value="utc"> UTC
<script>
// Global Variables
var selectedtimeformat;
// Set the selectedtimeformat variable on page load
$( document ).ready(function() {
setSelectedTimeFormat();
attachpicker();
});
$("input[type='radio']").click(function(){
var radioValue = $("input[name='timeformat']:checked").val();
if(radioValue != selectedtimeformat){
setSelectedTimeFormat();
if(selectedtimeformat == 'utc'){
$('input[name="datetimes"]').data('daterangepicker').remove();
attachpicker();
}else{
// Re-attach the DRP so the startDate, endDate, minDate and maxDate settings are updated for the UTC/local time choice
$('input[name="datetimes"]').data('daterangepicker').remove();
attachpicker();
}
}
}); // end function $("input[type='radio']").click(function(){...}
function setSelectedTimeFormat(){
selectedtimeformat = $("input[name='timeformat']:checked").val();
alert("selectedtimeformat: " + selectedtimeformat);
}
function attachpicker(){
if(selectedtimeformat == 'local'){
$('input[name="datetimes"]').daterangepicker({
"opens": 'right',
"drops": 'down',
"timePicker": true,
"locale": {
"format": 'MM/DD/YYYY'
},
"alwaysShowCalendars": true,
"ranges": {
'Today': [moment(), moment()],
'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'Last 7 Days': [moment().subtract(6, 'days'), moment()],
'Last 30 Days': [moment().subtract(29, 'days'), moment()],
'This Month': [moment().startOf('month'), moment().endOf('month')],
'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
},
"startDate": "04/08/2019",
"endDate": "04/10/2019",
"minDate": "04/05/2019",
"maxDate": "04/18/2019",
"timePickerIncrement": 10,
"timePicker24Hour": true
}); // <-- end of daterangepicker() constructor
}else{
// selectedtimeformat == 'utc'
$('input[name="datetimes"]').daterangepicker({
"opens": 'right',
"drops": 'down',
"timePicker": true,
"locale": {
"format": 'MM/DD/YYYY'
},
"alwaysShowCalendars": true,
"ranges": {
'Today': [moment(), moment()],
'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'Last 7 Days': [moment().subtract(6, 'days'), moment()],
'Last 30 Days': [moment().subtract(29, 'days'), moment()],
'This Month': [moment().startOf('month'), moment().endOf('month')],
'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
},
"startDate": "04/08/2019",
"endDate": "04/14/2019",
"minDate": "04/05/2019",
"maxDate": "04/18/2019",
"timePickerIncrement": 10,
"timePicker24Hour": true
}); // <-- end of daterangepicker() constructor
}
} //<-- end of function attachpicker()
$('input[name="datetimes"]').on('apply.daterangepicker', function(ev, picker) {
alert("apply.daterangepicker event fired");
});
</script>
</body>
</html>
Expected Result:
When I change the selected radio button and then select a pre-defined date range or click "apply" in the daterangepicker the apply.daterangepicker event should fire and an alert() popup should appear showing the event has fired.
i.e: the daterangepicker constructor should be removed and re-attached with new properties.
This should happen because my attachpicker() method is called when the radio button is changed.
Actual Result:
Instead when I change the selected radio button and then select a pre-defined date range or click "apply" in the daterangepicker I don't get the alert pop up showing that the apply event fired.
However...
When I change the selected Radio Button the startDate and endDate that appears in the textbox DOES update correctly.
With Local Radio Button selected:
"startDate": "04/08/2019"
"endDate": "04/10/2019"
UTC Radio Button selected:
"startDate": "04/08/2019"
"endDate": "04/14/2019"
So this tells me the daterangepicker constructor does get re-attached with new properties just that the apply event stops firing.
Why is that?

The remove() function you're calling removes any event listeners for the date range picker you're destroying.
Move your apply.daterangepicker listener creation into the attachpicker() function.

Related

How can get date in daterangepicker ranges selected date

I have to use daterangepicker and I can't figure out how to fetch the selected date in jquery.
$('#reportrange').daterangepicker({
startDate: start,
endDate: end,
ranges: {
'Today': [moment(), moment()],
'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'Last 7 Days': [moment().subtract(6, 'days'), moment()],
'Last 30 Days': [moment().subtract(29, 'days'), moment()],
'This Month': [moment().startOf('month'), moment().endOf('month')],
'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
}
}, cb);
//fetch seleted date
var get_date = $('#reportrange').val()
console.log("reportrange selected date:", get_date)
You must retrieve the data object:
$('#reportrange').data('daterangepicker').startDate;
$('#reportrange').data('daterangepicker').endDate;
You can also use this
<script>
$(function() {
$('input[name="daterange"]').daterangepicker({ opens: 'left' }, function(start, end, label) {
console.log("Your Select date range is: " + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD'));
});
});
</script>
For more detail : https://www.daterangepicker.com/
You can use default callback function like this
$(function() {
$('input[name="daterange"]').daterangepicker({
opens: 'left'
},
function(start, end, label) {
console.log("A new date selection was made: " + start.format('YYYY-MM-DD') + '
to ' + end.format('YYYY-MM-DD'));
});
});
$('#reportrange').data('daterangepicker').startDate;
$('#reportrange').data('daterangepicker').endDate;

change bootstrap date range picker's lables dynamically according to the selected language in cookie

I want to change date range picker's labels according to the language locale cookie which is set by user side. Right now, by default, I am using English labels, which I want to change them according to the cookie.
var locale = $.cookie('locale');
moment.locale(locale);
var start = moment();
var end = moment().add(29, 'days');
$('#Date').daterangepicker({
startDate: start,
endDate: end,
autoUpdateInput: false,
locale: {
cancelLabel: 'Clear'
},
ranges: {
'Today': [moment(), moment()],
'Tomorrow': [moment().add(1, 'days'), moment().add(1, 'days')],
'Next 7 Days': [moment(), moment().add(6, 'days')],
'Next 30 Days': [moment(), moment().add(29, 'days')],
'This Month': [moment().startOf('month'), moment().endOf('month')],
'Next Month': [moment().add(1, 'month').startOf('month'), moment().add(1, 'month').endOf('month')]
},
"alwaysShowCalendars": true
});
using moment.locale('custom language') helped to have the names of dates and month in localized language, but, how can I customize the labels of Today, Tomorrow and the others?
I want to get just the language id like 'en', 'fr' or others from cookie and then change the attributes in my javascript code according to that.
You should edit your locale object as below. Add "Apply" and "Cancel" on your cookie in desired language. Read from cookie and place them as I did below.
"locale": {
"format": "DD.MM.YYYY",
"separator": " - ",
"applyLabel": "Apply",
"cancelLabel": "Cancel",
"fromLabel": "From",
"toLabel": "To",
"customRangeLabel": "Custom",
"weekLabel": "W",
"daysOfWeek": [

Date Range Picker (JavaScript Component for Bootstrap) picks the wrong date on specific day

Currently I have been working with code which I am not the author and the user spotted a very specific problem I couldn’t find an answer to at all.
The page in question uses the Date Range Picker component to pick two dates (start and end).
Whenever someone clicks specifically on the day 16/10/2016 it is automatically shifted to 17/10/2016.
This was tested in multiple computers and browsers to no effect, I couldn’t trace down the issue with the debugger either.
Any other day, of any month, on any year, returns no problem at all. It only happens on the day 16/10/2016, and only if that date is the End date, it can be the Start date with no issues.
The current version: 2.1.24
Here is the code used:
<section class="col-md-4"> <!-- Selecionar Datas-->
<div class="form-group has-feedback has-feedback-right">
<input type="hidden" id="dt_inicio_afastamento">
<input type="hidden" id="dt_fim_afastamento">
<label class="control-label">Escolha o intervalo de datas</label>
<i class="form-control-feedback glyphicon glyphicon-calendar"></i>
<input id="escolhe_data" name="escolhe_data" class="input-mini form-control" type="text">
</div>
</section>
And the Script:
$('input[name="escolhe_data"]').daterangepicker({
showDropdowns: true,
autoApply: true,
autoUpdateInput: true,
locale: {
"format": "DD/MM/YYYY",
"separator": " - ",
"applyLabel": "Aplicar",
"cancelLabel": "Cancelar",
"fromLabel": "De",
"toLabel": "Até",
"customRangeLabel": "Outro",
"weekLabel": "S",
"daysOfWeek": ["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sab"],
"monthNames": ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro" ],
"firstDay": 1
},
alwaysShowCalendars: true
},
function(start, end, label) {
//console.log($('#escolhe_data').data());
});
$('#escolhe_data').on('apply.daterangepicker', function(ev, picker) {
$('#dt_inicio_afastamento').val(picker.startDate.format('YYYY-MM-DD'));
$('#dt_fim_afastamento').val(picker.endDate.format('YYYY-MM-DD'));
});
Based on the links posted by chiliNUT I was able to pinpoint the problem.
It was related to the end of daylight savings.
Having the user select the hour as well fixed the issue.
This can be done using the option "timePicker": true
in the $().daterangepicker({ }) configuration.
Thanks chiliNUT and everyone that helped!
Going to add to this..in case it helps but i did +1 the OP answer.
Here is some other features you can add as well. That does not use autoupdate and time zone will not affect it even if wrongly set.
$(function() {
$('input[name="escolhe_data"]').daterangepicker({
timePicker: true,
timePickerIncrement: 30,
locale: {
format: 'MM/DD/YYYY h:mm A'
},
ranges: {
'Today': [moment(), moment()],
'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'Last 7 Days': [moment().subtract(6, 'days'), moment()],
'Last 30 Days': [moment().subtract(29, 'days'), moment()],
'This Month': [moment().startOf('month'), moment().endOf('month')],
'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
}
});
$(window).scroll(function() {
if ($('input[name="daterange"]').length) {
$('input[name="daterange"]').daterangepicker("close");
}
});
});
DEMO: https://jsfiddle.net/norcaljohnny/kensoubf/

Added date filtering component to morris charts

I am using morris chart using http://morrisjs.github.io/morris.js/bars.html
one of the key problem i am facing is on add an option so that end user can filter data via data range or like say today or last one month etc.
That way the chart will be way more interactive and useful.
what would be the option to do that. i am using startBootStrap template which contains libraries for morris charts.
i used http://www.daterangepicker.com/#ex4 and linked it to my rest call to filter data
here is the brief code
function cb(start, end) {
$('#reportrange span').html(start.format('MMM D, YYYY') + ' - ' + end.format('MMM D, YYYY'));
//alert(start.format('MMM D, YYYY'));
$.ajax({ url: 'http://127.0.0.1:7101/MUDRESTService/rest/v1/msessionchart?onlyData=true&fields=Sessionlength,Sessiontime&limit=10',
type: 'get',
dataType: 'json',
success: function(output) {
console.log(output) ;
var ddata = JSON.stringify(output.items);
console.log('vik says');
console.log(ddata);
var arr = JSON.parse(ddata);
bar.setData(arr);
}
});
}
cb(moment().subtract(29, 'days'), moment());
$('#reportrange').daterangepicker({
ranges: {
'Today': [moment(), moment()],
'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'Last 7 Days': [moment().subtract(6, 'days'), moment()],
'Last 30 Days': [moment().subtract(29, 'days'), moment()],
'This Month': [moment().startOf('month'), moment().endOf('month')],
'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
}
}, cb);

angularjs daterangepicker not populating ngmodel

I'm trying to use http://www.daterangepicker.com/ with angularjs but I cannot get the value of ngModel updated. I have written the following directive but can anyone please tell me why scope.ngModel is always undefined?
angular.module('daterangepickerDirective', [])
.directive('daterangepicker', function() {
return {
restrict: 'A',
scope: {
ngModel: '='
},
link: function( scope, element, attrs ) {
console.log('scope.ngModel') // UNDEFINED. Why?
// Date range picker
element.daterangepicker({
locale: {
format: 'YYYY-MM-DD',
showDropdowns: true
},
ranges: {
'All Time': ['1900-01-01', moment()],
'Today': [moment(), moment()],
'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'Last 7 Days': [moment().subtract(6, 'days'), moment()],
'Last 30 Days': [moment().subtract(29, 'days'), moment()],
'This Month': [moment().startOf('month'), moment().endOf('month')],
'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
}
}).on("apply.daterangepicker",function(event){
scope.$apply(function() {
scope.ngModel.$setViewValue(event.date);//This will update the model property bound to your ng-model whenever the datepicker's date changes.
});
});
}
}
});
My HTML is simply
<input type="text" daterangepicker class="form-control" ng-model="selected_filters.date" />
Many thanks.

Categories