Bootstrap datepicker date range end date updating - javascript

I'm using this plugin https://bootstrap-datepicker.readthedocs.io/en/latest/
The problem i'm facing comes from using the "range" form of this plugin.
From the docs I understand there's a way to capture the "changeDate" event and do something when this happens, however, when the initial date is higher than the end date, the end date gets updated inmediately and I don't want this behaviour; what I want is the end date to be blank and to re-select the end date instead, but I have no clue how to capture and modify this.
Thanks in advance.
EDIT2: To clarify, this happens when both dates are already entered, but then, you select a start date that is higher to the end date.
EDIT: Here's the load code to show which options i'm using.
$('.input-daterange').datepicker({
format: "dd/mm/yyyy",
weekStart: 1,
language: lang,
daysOfWeekHighlighted: "0,6",
startDate: obj.initialDate,
orientation: "bottom auto",
autoclose: true,
showOnFocus: false,
maxViewMode: 'days',
keepEmptyValues: true,
templates: {
leftArrow: '<',
rightArrow: '>'
}
});

The snippet below shows the order of changeDate event firing. If a user set started date value that is later then finished date, then the changeDate event will be fired on finish input firstly.
$('.input-daterange').datepicker({
format: "dd/mm/yyyy",
weekStart: 1,
language: "en",
daysOfWeekHighlighted: "0,6",
startDate: "01/01/2017",
orientation: "bottom auto",
autoclose: true,
showOnFocus: true,
maxViewMode: 'days',
keepEmptyValues: true,
templates: {
leftArrow: '<',
rightArrow: '>'
}
});
$('.input-daterange').on('changeDate', function(e){
console.log(e.target.name + ": " + $(e.target).val());
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.min.js"></script>
<div class="input-group input-daterange">
<span class="input-group-addon">From</span>
<input type="text" name="start" class="form-control" value="22/05/2017">
<span class="input-group-addon">to</span>
<input type="text" name="finish" class="form-control" value="22/05/2017">
</div>
Therefore, it is neccessary to detect the reason of the firing. If the reason is not a user action then reset value of date. Also I find that preventDefault() method does not work for this event. Thus, I used two auxiliary variables to solve your question:
var userTarget = "";
var exit = false;
$('.input-daterange').datepicker({
format: "dd/mm/yyyy",
weekStart: 1,
language: "en",
daysOfWeekHighlighted: "0,6",
startDate: "01/01/2017",
orientation: "bottom auto",
autoclose: true,
showOnFocus: true,
maxViewMode: 'days',
keepEmptyValues: true,
templates: {
leftArrow: '<',
rightArrow: '>'
}
});
$('.input-daterange').focusin(function(e) {
userTarget = e.target.name;
});
$('.input-daterange').on('changeDate', function(e) {
if (exit) return;
if (e.target.name != userTarget) {
exit = true;
$(e.target).datepicker('clearDates');
}
exit = false;
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.min.js"></script>
<div class="input-group input-daterange">
<span class="input-group-addon">From</span>
<input type="text" name="start" class="form-control" value="20/05/2017">
<span class="input-group-addon">to</span>
<input type="text" name="finish" class="form-control" value="22/05/2017">
</div>

Related

Javascript Function Date Range Modification

I want to make my input type loggerTxt in date('F Y'); but I can't modify this log(data.dateFrom). I want to ask if it is possible to change it since I am a newbie.
<div class="wrapper">
<h3>Range</h3>
<input type="text" id="daterange">
<input type="text" id="range-from">
<input type="text" id="range-to">
<input type="text" id="loggerTxt">
</div>
</div>
<script type="text/javascript" src="../dist/duDatepicker.js"></script>
<script type="text/javascript">
function log (message) {
document.querySelector('#loggerTxt').value = message
}
document.addEventListener("DOMContentLoaded", function() {
duDatepicker.defaults({ auto: true, theme: 'dark', format: 'mmmm d, yyyy' });
duDatepicker('#daterange', {
range: true, outFormat: 'yyyy-mm-dd', fromTarget: '#range-from', toTarget: '#range-to',
clearBtn: true, theme: 'blue',
events: {
dateChanged: function (data) {
console.log('new date', data)
log(data.dateFrom)
}
}
})
})
</script>

Getting instance and field id of jQuery Datepicker

I've found a bunch of similar questions for this issue but none of their answers seems to work here. I have a Datepicker in a website where the input of a date is checked when the user is typing. It works well but I also want to have the date colored in realtime when the input is not valid. For that I need the id of the input field the Datepicker is associated with.
When using onClose function in Datepicker definiton, I get inst which is the instance of the current Datepicker object and by inst.id I get the field name. But this does not work in the parseDate function. I also can't pass on inst or make it global, because onClose is never executed before parseDate. I tried $(this).attr('id') as suggested somewhere but it returns undefined. My code (minimal example):
document.addEventListener("DOMContentLoaded", function () {
$(function () {
$(".dp").datepicker({
showOn: "focus",
showMonthAfterYear: false,
dateFormat: "dd.mm.yy",
onClose: function (dateText, inst) {
console.log("field name : ", inst.id); //works, inst.id is 'startDate'.
$("#" + inst.id + ".form-control.dp.hasDatepicker").css("color", "red"); //works, inst.id is 'startDate'.
}
});
$.datepicker.parseDate = function (format, value, settings) {
var field = $(this).attr("id"); //not working, field is null.
$("#" + field + ".form-control.dp.hasDatepicker").css("color", "red"); //not working, field is null.
};
});
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div class="row">
<label class="col-sm-3 col-form-label">{{ __('Start') }}</label>
<div class="col-sm-9">
<div class="input-group-addon">
<input type="text" class="form-control dp" id="startDate" name="start" value="">
<span class="glyphicon glyphicon-th"></span>
</div>
</div>
</div>
I would perform the date validity with a input event handler aside the date picker... Because that date check you wish to have is not a feature of datepicker.
So on input, evaluate the new Date value to add an .invalid class to the input like below:
$(document).ready(function () {
$(".dp").datepicker({
showOn: "focus",
showMonthAfterYear: false,
dateFormat: "dd.mm.yy"
});
$(".dp").on("input", function () {
// Remove the class on each new input
$(this).removeClass("invalid");
let currentVal = $(this).val();
console.log(currentVal);
// Split the value
let dateParts = currentVal.split(".");
// If incomplete
if (dateParts.length !== 3) {
$(this).addClass("invalid");
return;
}
// Create a date object to evaluate
let validDate = new Date(`${dateParts[2]}-${dateParts[1]}-${dateParts[0]} 00:00:00`);
console.log(validDate.toString());
// If the date is "invalid" and does not have 4 digits for the year (because it could be valid anyway... But obviously wrong)
if (validDate.toString() === "Invalid Date" || dateParts[2].length !== 4) {
$(this).addClass("invalid");
}
});
});
.dp.invalid{
color: red !important;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div class="row">
<label class="col-sm-3 col-form-label">{{ __('Start') }}</label>
<div class="col-sm-9">
<div class="input-group-addon">
<input type="text" class="form-control dp" id="startDate" name="start" value="">
<span class="glyphicon glyphicon-th"></span>
</div>
</div>
</div>
CodePen

Jquery datepicker subtract days

I'm using a jquery datepicker link in that i need to subtract 7 days from the current date. I've tried some code but its not working ie, days are not subtracting still showing current date itself. This is the code that i've tried yet. Any help is appreciable.
Demo fiddle
// datepicker
var $startDate = $('.start-date');
var $endDate = $('.end-date');
$startDate.datepicker({autoHide: true,format: 'yyyy-mm-dd'});
$startDate.datepicker("setDate", moment().subtract(7,'d').format('yyyy-mm-dd'));
$endDate.datepicker({
autoHide: true,
startDate: $startDate.datepicker('getDate'),
format: 'yyyy-mm-dd'
});
$endDate.datepicker('setDate', moment().format('yyyy-mm-dd'));
$startDate.on('change', function () {
$endDate.datepicker('setStartDate', $startDate.datepicker('getDate'));
});
// datepicker
As per the setDate this datePicker documentation - You are not using momentJS format date function correctly. You need to convert a date from YYYY-MM-DD to a date object like for example: Wed Sep 17 2020 00:00:00 GMT+1000 (Australian Eastern Standard Time)
For that you can use toDate() function of momentJS - Your code is working now as expected.
$startDate.datepicker("setDate", moment().subtract(7, 'd').toDate());
Or you can also use native Javascript new Date method like this below:
$startDate.datepicker("setDate", new Date(moment().subtract(7, 'd')));
You can also do this using just native JavaScript date function like this below instead of using moment library
var sub7Days = new Date();
sub7Days.setDate(sub7Days.getDate() - 7);
$startDate.datepicker("setDate", sub7Days);
Live Working Demo:
$(function() {
// datepicker
var $startDate = $('.start-date');
var $endDate = $('.end-date');
$startDate.datepicker({
autoHide: true,
format: 'yyyy-mm-dd'
});
$startDate.datepicker("setDate", moment().subtract(7, 'd').toDate());
$endDate.datepicker({
autoHide: true,
startDate: $startDate.datepicker('getDate'),
format: 'yyyy-mm-dd'
});
$endDate.datepicker('setDate', moment().toDate());
$startDate.on('change', function() {
$endDate.datepicker('setStartDate', $startDate.datepicker('getDate'));
});
});
<link rel="stylesheet" href="https://fengyuanchen.github.io/datepicker/css/datepicker.css">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>
<script src="https://fengyuanchen.github.io/datepicker/js/datepicker.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.0/moment.min.js" integrity="sha512-Izh34nqeeR7/nwthfeE0SI3c8uhFSnqxV0sI9TvTcXiFJkMd6fB644O64BRq2P/LA/+7eRvCw4GmLsXksyTHBg==" crossorigin="anonymous"></script>
<div class="col-md-3">
<input type="text" class="form-control start-date" id="datefrom" placeholder="Date From">
</div>
<div class="col-md-3">
<input type="text" class="form-control end-date" id="dateto" placeholder="Date To">
</div>
$(function() {
// datepicker
var $startDate = $('.start-date');
var $endDate = $('.end-date');
$startDate.datepicker({autoHide: true,format: 'yyyy-mm-dd'});
console.log(moment().subtract(7,'days').format('yyyy-mm-D'));
$startDate.datepicker("setDate", moment().subtract(7,'d').format('yyyy-mm-D'));
$endDate.datepicker({
autoHide: true,
startDate: $startDate.datepicker('getDate'),
format: 'yyyy-mm-dd'
});
$endDate.datepicker('setDate', moment().format('yyyy-mm-D'));
$startDate.on('change', function () {
$endDate.datepicker('setStartDate', $startDate.datepicker('getDate'));
});
// datepicker
});
<link rel="stylesheet" href="https://fengyuanchen.github.io/datepicker/css/datepicker.css">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>
<script src="https://fengyuanchen.github.io/datepicker/js/datepicker.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.0/moment.min.js" integrity="sha512-Izh34nqeeR7/nwthfeE0SI3c8uhFSnqxV0sI9TvTcXiFJkMd6fB644O64BRq2P/LA/+7eRvCw4GmLsXksyTHBg==" crossorigin="anonymous"></script>
<div class="col-md-3">
<input type="text" class="form-control start-date" id="datefrom" placeholder="Date From">
</div>
<div class="col-md-3">
<input type="text" class="form-control end-date" id="dateto" placeholder="Date To">
</div>
Changed moment().subtract(7,'d').format('yyyy-mm-dd') to moment().subtract(7,'d').format('yyyy-mm-D')

Unable to select days and hours when minDate and maxDate are on the same days with Eonasdan datetimepicker

I got an odd behaviour when using bootstrap-datetimepicker v. 4.17.47.
Here is my picker configuration:
format: 'YYYY-MM-DD HH:mm',
showTodayButton: true,
useCurrent: false,
showClear: true,
minDate: moment('{{ ts_beg }}'),
maxDate: moment('{{ ts_end }}')
When setting minDate and maxDate to the same day but with different hours, let's say 2018-2-1 00:00 and 2018-2-1 02:00, I am unable to choose both date and time:
Does anyone has a workaround to solve this issue ?
The problem, if not wrong, is because of the implementation of maxDate you can override this behavior using the functions, this way you will be able to select the date
Here a live example:
const format = 'YYYY-MM-DD HH:mm';
const MaxDate = moment('2018-02-01 02:00', format);
const MinDate = moment('2018-02-01 00:00', format);
$('#myDatepicker').datetimepicker({
format: format,
showTodayButton: true,
useCurrent: false,
showClear: true,
minDate: MinDate,
});
$('#myDatepicker').data("DateTimePicker").maxDate(MaxDate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdn.rawgit.com/Eonasdan/bootstrap-datetimepicker/25c11d79/build/css/bootstrap-datetimepicker.min.css" rel="stylesheet"/>
<br/>
<!--Space for the fiddle-->
<div class="container">
<div class="row">
<div class='col-sm-6'>
<div class="form-group">
<div class='input-group date' id='myDatepicker'>
<input type='text' class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
</div>
</div>

set datetimepicker's minimum date to another datetimepicker's selected date

I have two textboxes: txtETCdatefrom and txtETCdateto having classes datetimepicker1 and datetimepicker2 respectively:
<asp:TextBox ID="txtETCdatefrom" runat="server" CssClass="form-control datetimepicker1 col-md-6"></asp:TextBox>
<asp:TextBox ID="txtETCdateto" runat="server" CssClass="col-md-6 datetimepicker2 form-control"></asp:TextBox>
I am using datetimepicker with date only format on both classes(It is working fine if i set minDate to any specific date or moment()).
I want to set minimum date of datetimepicker2 to selected value of datetimepicker1 or value of txtETCdatefrom.
My datetimepicker code is:
$('.datetimepicker1').datetimepicker({
format: 'DD/MM/YYYY',
minDate: moment(),
});
$('.datetimepicker2').datetimepicker({
format: 'DD/MM/YYYY',
//minDate: moment(),
});
I searched about this and found answer for datepicker(using onSelect() function):
$('.datetimepicker1').datetimepicker({
format: 'DD/MM/YYYY',
minDate: moment(),
onSelect: function (date) {
var date1 = $('.datetimepicker1').datetimepicker('getDate');
var date = new Date(Date.parse(date1));
date.setDate(date.getDate() + 1);
var newDate = date.toDateString();
newDate = new Date(Date.parse(newDate));
$('.datetimepicker2').datetimepicker("option", "minDate", newDate);
}
});
$('.datetimepicker2').datetimepicker({
format: 'DD/MM/YYYY',
//minDate: moment(),
});
but it is not working for datetimepicker.
I also tried beforeShow() function like:
$('.datetimepicker1').datetimepicker({
format: 'DD/MM/YYYY',
minDate: moment(),
});
$('.datetimepicker2').datetimepicker({
format: 'DD/MM/YYYY',
//minDate: moment(),
beforeShow: function () {
$(".datetimepicker2").datetimepicker("option", {
minDate: $(".datetimepicker1").datetimepicker('getDate')
});
}
});
but all vain. Also tried onSelectDate() and onShow() functions as suggested in
Set max and min datetime in jquery datetimepicker
don't know what m doing wrong.
After including these functions in code the datetimepicker doesn't show up.
All help will be appreciated. Thank you.
I follow the docs in datepicker official website.
$(function () {
$('#datetimepicker1').datetimepicker({
format: 'DD/MM/YYYY',
minDate: moment(),
});
$('#datetimepicker2').datetimepicker({
format: 'DD/MM/YYYY',
});
$("#datetimepicker1").on("dp.change", function (e) {
var oldDate = new Date(e.date);
var newDate = new Date();
newDate.setDate(oldDate.getDate() + 1);
$('#datetimepicker2').data("DateTimePicker").minDate(newDate);
});
});
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdn.bootcss.com/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker.min.css" rel="stylesheet"/>
<script src="https://cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.js"></script>
<div class="container">
<div class="row">
<div class='col-sm-6'>
<div class="form-group">
<div class='input-group date' id='datetimepicker1'>
<input type='text' class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
</div>
<div class="row">
<div class='col-sm-6'>
<div class="form-group">
<div class='input-group date' id='datetimepicker2'>
<input type='text' class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdn.bootcss.com/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>

Categories

Resources