Bootstrap Datetimepicker on select event - javascript

How do I access a js function exampleFunction() when date is selected? I want to pass the date value there.
text_field_tag for datetimepicker (haml):
= text_field_tag 'start_day', class: 'datepick'
Javascript:
$(".datepick").datetimepicker({
timepicker: false,
format: 'd/m/Y',
closeOnDateSelect: true
});

You can achieve this by using below given code:
$("#datetimepicker6").on("dp.change", function (e) {
console.log(e.date);
});
I your case, it should be :
$(".datepick").on("dp.change",function(e){ exampleFunction(e.date) });
Remember this will call the example function on change in value of each datetimepicker, since you used class.
Reference URL: https://eonasdan.github.io/bootstrap-datetimepicker/

If this is the plugin you are using then it would be Like this.
$(".datepick").datetimepicker({
onChangeDateTime:exampleFunction
});
function exampleFunction(){
console.log("Date Selected")
}
For full option list Reference:
http://xdsoft.net/jqplugins/datetimepicker/
Hope it helps.

Try this :
$(".datepick").datetimepicker({
timepicker: false,
format: 'd/m/Y',
closeOnDateSelect: true
}).on('dp.change', function (ev) {
exampleFunction() ;//your function call
});

Simply:
$(".datepick").datetimepicker({
format: 'd/m/Y',
}).on('select', function (e) {
console.log('on select event');
});

Related

Select only start date in Date Range and Set +7 days for End (Bootstrap Date Range Picker)

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/

Backbone qunit testing: trigger onSelect event on date picker?

I'm trying to write my first qunit tests using my jquery date picker module, right now I want to trigger the onSelect method I am using but this doesn't seem to get picked up in the tests, here is my simple test:
JS
this.dateSelectorView.$el.on('onSelect', function() {
assert.ok(true, 'true succeeds');
});
Here is the date picker:
this.$el.datepicker({
dateFormat: Common.DATE_FORMAT,
showOtherMonths: true,
selectOtherMonths: true,
beforeShowDay: function (date) {
return _.availableDates(date, Common.availableDates);
},
onSelect: function() {
Backbone.Events.trigger('date:selected', this.value);
}
});
Listen to the view itself,
when invoking the date picker, trigger the event to the view
onSelect: _.bind(function() {
this.trigger('date:selected', this.value);
},this)
I use "bind" to expose the outer scope(the view)
Then, in your View creating the the datepicker, listen to the change event.
this.listenTo(this.dateSelectorView, 'date:selected', this.callback);

2 Bootstrap Datepickers: How to change min and max dates?

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

Bootstrap Datepicker on change firing 3 times

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

How to get current viewMode property from "Bootstrap Datepicker"

How to get current viewMode property from "Bootstrap Datepicker"?
I initialize the control with viewMode= 'years' and I want to close datepicker on changeDate event, only when viewMode='days'.
The user selects a year, then a month, and finally a day. In that moment the control must be closed.
This is the code:
$("#date").datepicker(
{viewMode: 'years',
format: 'dd/mm/yyyy'
});
$('#date').on('changeDate', function (ev) {
//close when viewMode='0' (days)
})
Can anyone help?
Check this : http://jsfiddle.net/nAXnM/
HTML
<input type="text" class="span2" value="02/16/12" data-date-format="mm/dd/yy" id="dp2" >
JS
$("#dp2").datepicker({
viewMode: 'years',
format: 'dd/mm/yyyy'
});
$('#dp2').on('changeDate', function (ev) {
//close when viewMode='0' (days)
if(ev.viewMode === 'days'){
$('#dp2').datepicker('hide');
}
})
If you're using the forked version of Bootstrap Datepicker, to close the UI widget when a date is selected, set the autoclose option to true:
$("#date").datepicker({
autoclose: true
});

Categories