Setting date range picker start date to blank - javascript

I have a daterange picker based on http://www.daterangepicker.com 's daterange picker and I want to set the start date to empty. This will work for what I want to do.
I'm using an text input field to get the dates
</span><input type="text" class="form-control" id="reservation" />
On the site there is an example of setting "Input Initially Empty" but I couldn't get it to work. Basically I don't know where to set it as it seems.
My daterange picker is inside a partial view and it called by another view. Page scripts are set in the view which calls the partial one. On the daterangepicker.js script I found these lines;
//default settings for options
this.parentEl = 'body';
this.element = $(element);
this.startDate = moment().startOf('day');
this.endDate = moment().endOf('day');
this.minDate = false;
this.maxDate = false;
this.dateLimit = false;
this.autoApply = false;
this.singleDatePicker = false;
this.showDropdowns = false;
this.showWeekNumbers = false;
this.timePicker = false;
this.timePicker24Hour = false;
this.timePickerIncrement = 1;
this.timePickerSeconds = false;
this.linkedCalendars = true;
this.autoUpdateInput = true;
this.ranges = {};
As far as I can tell they are based on moment.js. I tried manipulating this.startDate but couldn't manage to set it to a blank value. using this.startdate = null made the whole date range picker stop working so I guess I need something like empty date equivalent of moment.js. Or something entirely different.
Can anyone show me how to do it?

Input Initially Empty
<input type="text" name="datefilter" value="" />
<script type="text/javascript">
$(function() {
$('input[name="datefilter"]').daterangepicker({
autoUpdateInput: false,
locale: {
cancelLabel: 'Clear'
}
});
$('input[name="datefilter"]').on('apply.daterangepicker', function(ev, picker) {
$(this).val(picker.startDate.format('MM/DD/YYYY') + ' - ' + picker.endDate.format('MM/DD/YYYY'));
});
$('input[name="datefilter"]').on('cancel.daterangepicker', function(ev, picker) {
$(this).val('');
});
});
</script>
or
//daterangepickers
//moment.locale('tr');
moment.locale("#SessionHelper.CurrentLanguageTwoChar");
$(".date-control").daterangepicker({
singleDatePicker: true,
showDropdowns: true,
//timePicker: true,
//timePicker24Hour: true,
//timePickerSeconds: true,
minYear: parseInt(moment().subtract(10, 'years').format('YYYY'),10),
maxYear: parseInt(moment().add(10, 'years').format('YYYY'), 10),
autoUpdateInput: false,
singleClasses: "",
locale: {
//format: 'DD.MM.YYYY HH:mm:ss'
//format: 'DD.MM.YYYY'
}
});
$('.date-control').on('apply.daterangepicker', function (ev, picker) {
$(this).val(picker.startDate.format('L'));
});
$('.date-control').on('cancel.daterangepicker', function (ev, picker) {
$(this).val('');
});
http://www.daterangepicker.com/#example5
https://github.com/dangrossman/daterangepicker/issues/815

autoUpdateInput: false
function (chosen_date) {
$('.form-datetime').val(chosen_date.format('YYYY-MM-DD'));
}

I solved this issue using this....I hope this issue could help you.
Input Tag
<div class="form-group">
<label>Due date:</label>
<div class="input-group">
<input type="text"
class="form-control float-right"
id="duetime"
name="due_time"
autocomplete="off"
/>
</div>
</div>
script
<script>
$(function(){
$("#duetime").daterangepicker({
autoUpdateInput: false,
minYear: 1901,
showDropdowns: true,
singleDatePicker: true,
timePicker: true,
timePicker24Hour: false,
timePickerIncrement: 05,
drops: "up",
locale: {
format: 'MM/DD/YYYY hh:mm A'
}
}).on("apply.daterangepicker", function (e, picker) {
picker.element.val(picker.startDate.format(picker.locale.format));
});
});
</script>
Note: I found this from this source https://github.com/dangrossman/daterangepicker/issues/815#issuecomment-493323964

To set default value of date range picker to null,
Inside your function set autoUpdateInput to false
autoUpdateInput: false,

for the daterangepicker include from date and to date
please flowing this code set start date to blank
$('.form-datetime').daterangepicker({autoUpdateInput: false}, (from_date, to_date) => {
console.log(from_date.toDate(), to_date.toDate());
$('.form-datetime').val(from_date.format('DD/MM/YYYY') + ' - ' + to_date.format('DD/MM/YYYY'));
});
Thanks.

Related

How to configure datetimepicker to work correctly when only the date is selected

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- XDSoft DateTimePicker -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.full.min.js"></script>
<body>
<input id="datetimepicker" type="text" >
<script>
jQuery('#datetimepicker').datetimepicker({
minDate: 0, // today
minTime: 0, // now
defaultSelect: false,
inline: true,
});
</script>
</body>
The problem is that when I only select the date, datetimepicker
gets initialized with current time passing the validation, which I don't want because I'm
using 60min default step and also because it's counterintuitive since
I didn't select any time ( nor one it's selected by default - which is fine ).
Any ideas on how I can make it work properly when submitting the form? I would like to stick
with the inlined version.
I haven't used datetimepicker before however I messed around with it and think I have something like what you're asking for. First I wrapped your script in a $(document).ready() as this is recommended so the page loads correctly.
I then added your input and a button to a form element so we can submit the form and identify it via a form id. I commented out the minTime: 0 as it greys out hours before the current hour even on future dates. I then added an array for the allowTimes property with hourly intervals (you can update how you like). Although I now don't see a time being highlighted automatically once a date is chosen, it seems to be automatically choosing the current time. To get around this I added a boolean onTimeChosen that becomes true only when the user selects a time.
That with a simple if statement means the user can't progress unless they've selected a time.
<body>
<form id="myForm">
<input id="datetimepicker" type="text" required>
<button type="submit" id="form-submit">Submit</button>
</form>
<script>
$(document).ready(function() {
let onTimeChosen = false;
jQuery('#datetimepicker').datetimepicker({
minDate: 0, // today
// minTime: 0, // now
defaultSelect: false,
inline: true,
datetimepicker: false,
onSelectTime: function() {
onTimeChosen = true;
},
allowTimes:[
'00:00', '01:00', '02:00', '03:00', '04:00', '05:00',
'06:00', '07:00', '08:00', '09:00', '10:00', '11:00',
'12:00', '13:00', '14:00', '15:00', '16:00', '17:00',
'18:00', '19:00', '20:00', '21:00', '22:00', '23:00'
],
});
$("#myForm").submit(function(event) {
if(!onTimeChosen){
alert("You need to select a time");
event.preventDefault();
} else {
var d = $('#datetimepicker').datetimepicker('getValue');
alert(d.toDateString());
}
})
});
</script>
</body>
For setting future hours list automatically:
...
allowTimes: generateTimes(new Date()),
onChangeDateTime: logic,
...
function generateTimes(date) {
var result = [];
var nowHour = date.getHours();
for(var i = nowHour + 1; i < 24; i++){
result.push(i + ":00");
}
return result;
}
function generateAllTimes() {
var result = [];
for(var i = 0; i < 24; i++){
result.push(i + ":00");
}
return result;
}
var logic = function(currentDateTime)
{
var date = new Date();
if(currentDateTime.getDate() == (date.getDate()))
{
this.setOptions
({
allowTimes: generateTimes(new Date()),
});
}
else
{
this.setOptions
({
allowTimes: generateAllTimes(),
});
}
}

multiple bootstrap datepicker's on the same page with extending form

It's maybe old question to add more then date-picker's on the same page. But I have a different case here.
used library
https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js
Here is the script for the datepicker
<script>
$(document).ready(function () {
$('.datepicker').datepicker({
keyboardNavigation: false,
forceParse: false,
todayHighlight: true
});
});
</script>
now multiple date-picker will work fine on the same page.
{!! Form::text('expiry_date', null, ['data-format'=>'D, dd MM yyyy', 'class'=>'form-control datepicker', 'placeholder'=>'yyyy-mm-dd']) !!}
{!! Form::text('expiry_date', null, ['data-format'=>'D, dd MM yyyy', 'class'=>'form-control datepicker', 'placeholder'=>'yyyy-mm-dd']) !!}
but the second datepicker here comes from extending form script
<script>
let counter = 1;
let limit = 10;
function addInput(divName) {
if (counter === limit) {
alert("You have reached the limit of adding " + counter + " inputs");
} else {
let newdiv = document.createElement('div');
newdiv.innerHTML = '<div class = "col-md-12"> <h4>Package ' + (counter + 1) + ' </h4> ...<div class="col-sm-6"><div class="form-group"><div id="date-popup2" class="input-group date">{!! Form::text("expiry_date", null, ["data-format"=>"D, dd MM yyyy", "class"=>"form-control datepicker", "placeholder"=>"yyyy-mm-dd"]) !!}<span class="input-group-addon"><i class="fa fa-calendar"></i></span></div></div></div>...';
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
</script>
When the second datepicker populate it dose't work. Any idea.
It's because you're initiating the .datepicker(), before you have rendered the second datepicker object.
Maybe try something similar to this:
$(function() {
$(this).datepicker();
$('#date').append('<p>Other Date: <input onfocus="dateme(this);" type="text" class="datepicker"></p>')
});
function dateme(x){
$(x).datepicker();
}
Just to explain what's going on here, I append a new datepicker input, which has an onfocus="" attribute, which calls a function containing the .datepicker function when the input is in focus.
Codepen Example: https://codepen.io/lthomas122/pen/XQyOMm
For fast isolation
$('.datepick').each(function(){
$(this).datepicker({
keyboardNavigation: false,
forceParse: false,
todayHighlight: true
});
// apply the rest
});
this here it will keep it isolated

Bootstrap datetimepicker disable future date and time

I am trying to disable future hours within today using disabledTimeIntervals but it doesn't seem to work.
What I need to do is disable future hours in timepicker for today only, because disabling dates I can do with maxDate.
<input class="form-control input-sm pull-left " id="dp" placeholder="To" type="text">
$('#dp').datetimepicker({
maxDate: '0',
disabledTimeIntervals: [[moment(), moment().hour(24).minutes(0).seconds(0)]],
format: 'm/d/Y H:i A',
timepicker: true,
});
JSFIDDLE: https://jsfiddle.net/3oxmccjq/1/
You can use maxTime option and function onChangeDateTime to set the minTime according to the selected date.
The comparison between dates is up to you :-)
var today = new Date();
var options = {
maxDate: new Date(),
maxTime: new Date(),
disabledTimeIntervals: [
[moment(), moment().hour(24).minutes(0).seconds(0)]
],
format: 'm/d/Y H:i A',
timepicker: true,
onChangeDateTime: function(date) {
// Here you need to compare date! this is up to you :-)
if (date.getDate() === today.getDate()) {
this.setOptions({maxTime: new Date()});
} else {
this.setOptions({maxTime: false});
}
}
};
$('#dp').datetimepicker(options);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.4/build/jquery.datetimepicker.full.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.2.1/moment.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.4/jquery.datetimepicker.css" rel="stylesheet" />
<input class="form-control input-sm pull-left " id="dp" placeholder="To" type="text">
The datetimepicker you are using in your jsfiddle have no options as disabledTimeIntervals and that's why it is not working. You should use disabledMinTime & disabledMaxTime
As for the solution I am guessing you want to disable all future hours for today but still want to allow future dates with all the possible time. Here is a jsfiddle for same :-
https://jsfiddle.net/sahilbatla/zpzL2po3/
Code looks like this :-
var today = new Date();
var todayEndOfDay = new Date().setHours(23,59,59,999);
$('#dp').datetimepicker({
disabledMinTime: today,
disabledMaxTime: todayEndOfDay,
format: 'm/d/Y H:i A',
timepicker: true,
onChangeDateTime: function(date) {
if (date.getDate() !== today.getDate()) {
this.setOptions({disabledMinTime: false, disabledMaxTime: false})
} else {
this.setOptions({disabledMinTime: today, disabledMaxTime: todayEndOfDay})
}
}
});

How to restrict date and month not valid in Jquery / Javascript

This is my code
//Put our input DOM element into a jQuery Object
var $jqDate = jQuery('input[name="jqueryDate"]');
//Bind keyup/keydown to the input
$jqDate.bind('keyup','keydown', function(e){
//To accomdate for backspacing, we detect which key was pressed - if backspace, do nothing:
if(e.which !== 8) {
var numChars = $jqDate.val().length;
if(numChars === 2 || numChars === 5){
var thisVal = $jqDate.val();
thisVal += '/';
$jqDate.val(thisVal);
}
}
});
<div style="font-family: Helvetica,Arial,sans-serif; font-size: 12px; line-height: 150%;">
<strong>HTML5 "date" input type:</strong> <input type="date" name="html5date"><br>
<strong>jQuery "date" input type mimic:</strong> <input type="text" name="jqueryDate" placeholder="dd/mm/yyyy"><br>
Key Input: <span id="keyP">null</span>
</div>
In the above code i have a textbox . In that textbox user enter date manually . It takes date format worked . But user enter day more than 31 and month 12 it not accept.How to restrict date and month by using Jquery or Javascript.
This is Jsfiddle :- https://jsfiddle.net/ChrisCoray/hLkjhsce/
You Need to add 'datePicker'as class name
$(".datePicker").datepicker({
dateFormat: 'd/mm/yy',
changeMonth: true,
changeYear: true,
firstDay: 1,
minDate: Date.parse("1900-01-01"),
maxDate: Date.parse("2100-01-01"),
yearRange: "c-90:c+150"
});
// validation in case user types the date out of valid range from keyboard : To fix the bug with out of range date time while saving in sql
$(function () {
$.validator.addMethod(
"date",
function (value, element) {
var minDate = Date.parse("1900-01-01");
var maxDate = Date.parse("2100-01-01");
var valueEntered = Date.parse(value);
if (valueEntered < minDate || valueEntered > maxDate) {
return false;
}
return !/Invalid|NaN/.test(new Date(minDate));
},
"Please enter a valid date!"
);
});

Two datetimepickers

I am using Bootstrap datetimepickers to input start and end datetimes.
Is there any way to make sure/validate that the end datetimepicker is not before the start datatimepicker?
$('#start').datetimepicker({
format: 'dd-mm-yyyy hh:ii',
autoclose: true,
startDate: date
})
$('#end').datetimepicker({
format: 'dd-mm-yyyy hh:ii',
autoclose: true,
startDate: date
})
i can suggest this instead of bootstrap, look here and just replace the min option
https://jqueryui.com/datepicker/#min-max
$('#DatePicker').datetimepicker({
timepicker : false,
format : 'd.m.Y',
minDate : '-1969/12/31'
})
You have to set a min date, it should be dinamically set that way it will work with different dates
I think you can check it when the end date is set:
$('#end').change(function(){
if(this.val() != ""){
var start_date = $('#start').val();
var end_date = $('#end').val();
if(start_date <= end_date){
//After
}else{
//Before
}
}
});
Or at the form submission:
$('#submit').click(function(){
var start_date = $('#start').val();
var end_date = $('#end').val();
if(start_date <= end_date){
//After
}else{
//Before
}
});

Categories