How can I clear input text on datetimepicker? - javascript

Demo and full code like this :
https://jsfiddle.net/oscar11/yfjvd200/
I want the datepicker and timepicker not filled when loaded the first time. I want the datepicker or timepicker to filled when the user clicks on the input text of each. Eg user click on timepicker text input then time will be filled
I try use this :
$('#datepicker').val("");
$('#timepicker').val("");
But it does not work
How can I do it?

You found the right trick!
$('#datepicker').val("");
$('#timepicker').val("");
But you are not doing it at the right moment. Place that AFTER the pickers have been instanciated.
To fill the time on focus, add this .on() to timepicker:
$('#timepicker').datetimepicker({
minDate: moment().add(300, 'm'),
})
.on('focus', function(e){
if( $(this).val() == "" ){
$(this).data("DateTimePicker").minDate(moment().add(300, 'm'));
}
});
Fiddle

You just need to write these lines to end of your function :
$('#datepicker').val("");
$('#timepicker').val("");
You can use this code :
$(function () {
console.clear();
$('#datepicker').datetimepicker({
minDate: moment().add(300, 'm').startOf("day")
})
.val(moment().add(300, 'm').format("DD-MM-YYYY")) // To set correct "valid" date from start
.on('dp.change', function(e){
var now = moment().format("X");
//console.log(e.date.format("X"));
//console.log(now);
// Comparing selected date (moment object) in milliseconds
if(e.date.format("X")+(300*60*1000) > now ){
console.log("above 5 hours, unlocking time.");
$('#timepicker').data("DateTimePicker").minDate(false);
}else{
console.log("below 5 hours, locking time (and probably resetting the value to min...)");
$('#timepicker').data("DateTimePicker").minDate(moment().add(300, 'm'));
}
});
$('#timepicker').datetimepicker({
minDate: moment().add(300, 'm'),
});
$('#datepicker').val("");
$('#timepicker').val("");
});

Have a look at this fiddle https://jsfiddle.net/lamp03/yfjvd200/9/. I have commented some lines
$(function () {
//$('#datepicker').val("");
//$('#timepicker').val("");
console.clear();
$('#datepicker').datetimepicker({
minDate: moment().add(300, 'm').startOf("day")
})
//.val(moment().add(300, 'm').format("DD-MM-YYYY")) // To set correct "valid" date from start
.on('dp.change', function(e){
var now = moment().format("X");
//console.log(e.date.format("X"));
//console.log(now);
// Comparing selected date (moment object) in milliseconds
if(e.date.format("X")+(300*60*1000) > now ){
console.log("above 5 hours, unlocking time.");
$('#timepicker').data("DateTimePicker").minDate(false);
}else{
console.log("below 5 hours, locking time (and probably resetting the value to min...)");
$('#timepicker').data("DateTimePicker").minDate(moment().add(300, 'm'));
}
});
$('#timepicker').datetimepicker({
//minDate: moment().add(300, 'm'),
}).on('dp.change', function(e){ $('#timepicker').data("DateTimePicker").minDate(moment().add(300, 'm'));});
});

Related

jquery datetimepicker maxTime and minTime not being updated onShow

I'm using two datetimepickers inputs and am trying to grey out and prevent users from selecting invalid start and end times based on previous input in the datepickers. For example end time should never be before start time and vice-versa.
For some reason the times correctly start off greyed out, but when I try to select an earlier start time, the minTime doesn't change for the #availibility_end_time datepicker.
I found a similar close solution but it hasn't seemed to work for me.
$('#availability_start_time').datetimepicker({
format: 'd/m/Y - H:i',
timepicker: true,
onShow: function( selected_time ){
this.setOptions({
value:$('#availability_end_time').val(),
maxTime: $('#availability_end_time').val()
});
}
});
$('#availability_end_time').datetimepicker({
format: 'd/m/Y - H:i',
timepicker: true,
onShow: function( selected_time ){
this.setOptions({
value: $('#availability_end_time').val(),
minTime: $('#availability_start_time').val()
});
}
});

Allow datepicker to show only specific month

I'm trying to crate a datepicker from jQuery.
Users will allow to choose only June to September in each year from 2016-2020.
(So I don't think minDate and maxDate will work here)
I tried using the "beforeShowDay" as mentioned in
Disable specific months JqueryUI datepicker
The code was successfully disable users from picking the date outside from June to September but they can still choose January-December from the month dropdownlist (of datepicker).
What I want to do is limit the datepicker month-drop-down-list to show only June to September.
$(document).ready(function() {
$("#datepicker").datepicker({
changeMonth: true,
changeYear: true,
yearRange:'2016:2020',
minDate:0,
beforeShowDay: disableSpecificWeekDays
});
var monthsToDisable = [0,1,2,3,4,9,10,11];
var endMonth=[8];
function disableSpecificWeekDays(date) {
var month = date.getMonth();
if ($.inArray(month, monthsToDisable) !== -1) {
return [false];
}
return [true];
}
$("#datepicker").datepicker("setDate",'06/01/2016');
});
I don't see any options that would allow you to adjust this. I have a hacky solution that will probably do the job for most use cases, but that's your call. What I have done here is remove the unwanted select items from the datepicker list each time it gets updated. I had to add a short delay as jQuery UI takes a second to generate its code.
var removeDisabledMonths = function() {
setTimeout(function() {
var monthsToDisable = [0,1,2,3,4,9,10,11];
$.each(monthsToDisable, function(k, month) {
var i = $('#ui-datepicker-div select.ui-datepicker-month').find('option[value="'+month+'"]').remove();
});
}, 100);
};
//datepicker
$("#datepicker").datepicker({
changeMonth: true,
changeYear: true,
yearRange:'2016:2020',
minDate:0,
beforeShowDay: disableSpecificWeekDays,
// Added this --
onChangeMonthYear: function(year, month, obj) {
removeDisabledMonths();
}
});
//initial hide
setTimeout(function() {
removeDisabledMonths();
}, 1000);
Note that I had to call the function with a 1 second delay after the datepicker was initialized in order to get the months to hide the first time. Hacky, but if you are only looking to adjust the UI for the user, it just may do the job.
Well, Christ's code will activate itself after you choose some month/date.
If you don't, the January,Feb..... still being shown.
Therefore I add "beforeShow:" and connect it to removeDisabledMonths();
Now it works better.
$("#datepicker").datepicker({
changeMonth: true,
changeYear: true,
yearRange:'2016:2020',
minDate:0,
beforeShowDay: disableSpecificWeekDays,
onChangeMonthYear: function(year,month,obj){
removeDisabledMonths();
}
});
var monthsToDisable = [0,1,2,3,4,9,10,11];
function disableSpecificWeekDays(date) {
var month = date.getMonth();
var day=date.getDate();
if ($.inArray(month, monthsToDisable) !== -1) {
return [false];
}
return [true];
}
$("#datepicker").datepicker("setDate",'06/01/2016');er code here
$( ".selector" ).datepicker( "option", "defaultDate", "2019-09-01" );
$( ".selector" ).datepicker( "option", "minDate","2019-09-01");
$( ".selector" ).datepicker( "option", "maxDate","2019-09-30");
This displays only the month of September in the calendar and stops the user from accessing other months.

bootstrap datepicker invalid date issue when i click date twice?

I'm using bootstrap datepicker and I got invalid date issue in a specific case. If I click today date it works fine but when I click the same date again it gives out invalid date issue.
Same is the case for all the dates as I have seen other plugins where I can't find this issue.
html:
<input id="dp1" type="text" class="form-control input-sm" placeholder="Data CheckIn">
javascript:
$("#dp1").datepicker({
format: "mm-dd-yyyy",
viewMode: 'days',
todayHighlight: true
}).on('changeDate', function (ev) {
var a = $('#dp1').datepicker('getDate');
$(this).datepicker('hide');
alert(a);
});
jsfiddle example
var currentDate;
$('#dp1').datepicker({
format: "mm-dd-yyyy",
viewMode: 'days',
todayHighlight: true
// currently picked date
}).on('show', function() {
currentDate = $(this).val();
})
// if no date picked replace with previous date
.on('changeDate', function(ev) {
if ($(this).val() === '' || $(this).val() === null) {
$(this).val(currentDate).datepicker('update');
}
var a = $('#dp1').datepicker('getDate');
$(this).datepicker('hide');
alert(a);
});
After an effort of a day I solved issue by myself by doing a little change in plugin.
In bootstrap-datepicker.js method _toggle_multidate line no 1024 has been commented.
else if (ix !== -1)
{
//this.dates.remove(ix);
}
and it will work like a charm. I hope this can help.
Please try and do let me know if this case solve your issue
Thanks
you can use delegate, it does work fine
$("body").delegate('.date' ,'focusin', function() {
$(this).datepicker({
autoclose: true,
viewMode: 'days',
todayHighlight: true
});
});
it is not an issue.When you click first time it will set the selected date on input when you click again on same date again so it will deselect that date.

How to get the selected date from jquery datepicker

I am using jquery datepicker to show a calendar.Now as per my requirement i want to get the date selected by the user in my jquery variable which i will use in my application but i am not able to get the date ..
Here is the code for datepciker
<div id="datepicker"></div>
and here i am trying to get the selected code..
$(document).ready(function () {
$("#datepicker").datepicker({
onSelect: function (dateText, inst) {
var date = $(this).val();
alert(date);
}
});
});
But, I am not able to get the date ..Please help me ..Thanks..
This should do the trick
$(function() {
$("#datepicker").datepicker();
$("#datepicker").on("change",function(){
var selected = $(this).val();
alert(selected);
});
});
It's basic but here is a jsfiddle with it alerting the selected date when selected
update to change the date format
$(function() {
$( "#datepicker" ).datepicker({ dateFormat: "yy-mm-dd" });
$("#datepicker").on("change",function(){
var selected = $(this).val();
alert(selected);
});
});
jsfiddle
3rd update
$(function() {
$("#datepicker").datepicker({
dateFormat: "yy-mm-dd",
onSelect: function(){
var selected = $(this).val();
alert(selected);
}
});
});
I have used a little more of the native markup for datepicker ui here try this and see if you get the alert as you are after.
4th Update
$(function() {
$("#datepicker").datepicker({
dateFormat: "yy-mm-dd",
onSelect: function(){
var selected = $(this).datepicker("getDate");
alert(selected);
}
});
});
The 4th method uses $(this).datepicker("getDate") instead of $(this).val() as $(this).datepicker("getDate") returns a date object and $(this).val() returns the date as a string.
Depending on your needs select which one is appropriate.
(Added 4th method and explanation of the difference after #TimothyC.Quinn commented that the getDate being the correct method)
Though, question is answered, for people who just want a date object or set a date with specific format. There is simple functions jQuery provides. Here's working jsfiddle
$( "#datepicker" ).datepicker({ dateFormat: "dd-mm-yy" });
$("#datepicker").datepicker('setDate', '10-03-2020');
// pass string of your format or Date() object
$("#datepicker").datepicker('getDate');
// returns Date() object
$("#another_datepicker").datepicker('setDate', $("#datepicker").datepicker('getDate'));
// pass string of your format or Date() object
Try
$("#datepicker").datepicker({
onSelect:function(selectedDate)
{
alert(selectedDate);
}
});
OR
$("#datepicker").datepicker({
onSelect:function (dateText, inst)
{
alert(inst);
}
});
try this
$('.selector').datepicker({
onSelect: function(dateText, inst) { ... }
})
you have two elements with the class .datepicker, the selector won't know which element to choose from. So, you'll have to specify the name of the input you're trying to get the date from
first = $(".datepicker[name=datepicker1]").datepicker('getDate');
second = $(".datepicker[name=datepicker2]").datepicker('getDate');
You can use the changeDate event outlined here instead of onSelect and then reference e.date or e.dates. See the JSON below.
HTML:
<div id='QA'></div>
<div id='datepicker'></div>
JS:
<script type="text/javascript">
$(function() {
$('#datepicker').datepicker({
clearBtn: true,
todayHighlight: false,
multidate: true
}) .on('changeDate', function(e){
$('#QA').html(JSON.stringify(e));
});
});
/*
{
"type":"changeDate",
"date":"2015-08-08T07:00:00.000Z",
"dates":[
"2015-08-08T07:00:00.000Z"
],
"timeStamp":1438803681861,
"jQuery21409071635671425611":true,
"isTrigger":3,
"namespace":"",
"namespace_re":null,
"target":{
},
"delegateTarget":{
},
"currentTarget":{
},
"handleObj":{
"type":"changeDate",
"origType":"changeDate",
"guid":52,
"namespace":""
}
}
*/
</script>
The ideal way is to get the date and convert it to a common format and utilize the same. (may passing to server or so.)
$("#datepicker").datepicker('getDate').toISOString()
so it will get the date in ISO stander.
All code is for Bootstrap Datepicker
var calendar = $('#calendar').datepicker("getDate"); // Ex: Tue Jun 29 2021 00:00:00 GMT+0600 (Bangladesh Standard Time)
or
var calendar = $('#calendar').data('datepicker').getFormattedDate('yyyy-mm-dd'); // Ex: 2021-06-30
if(calendar){
alert(calendar);
} else {
alert('null');
}
If you need it in specific format like '2021/09/28':
$.datepicker.formatDate('yy/mm/dd',
$('.date-picker-2').datepicker("getDate")
);
Here is how to get Date object from datepicker in the onSelect event:
$("#datepickerid").datepicker({
onSelect: function (dateText, inst) {
var date_obj = $(this).datepicker('getDate');
}
});
I find it strange that the onSelect caller would not return the date object by default.

Hidden value changed, datepicker will reload

I have a question on how to make sure whenever this hidden value changed, the datepicker will reload. Because the datepicker will used the hidden value to highlight the days. So whenever the hidden value changed, the highlighted days in datepicker also will change.
Here my code so far. $("#dates").val() is a hidden value. sample of the value is 2013/11/11-2013/11/17. This value will highlight the whole week (mon-sun). There's a previous and next button, which will changed the $("#dates").val() by week eg:
2013/11/18-2013/11/24, 2013/11/25-2013/12/1
I have no problem to trigger if the hidden value is changed, the problem is I want the datepicker to reload once the hidden value changed. so that the highlighted week while changed accordingly. currently whenever the hidden value change, the highlighted week will remain the same.
I did try to used $( "#datepicker" ).datepicker( "refresh" ); whenever the hidden value changed, but still no luck. Please help me. Thanks
$(document).ready(function() {
var dates = $("#dates").val();
var lt = dates.split("-");
var ts = lt[0].split("/");
var te = lt[1].split("/");
var date1 = new Date(ts[0], ts[1]-1, ts[2]);
var date2 = new Date(te[0], te[1]-1, te[2]);
$(function(){
$('#datepicker').datepicker({
dateFormat: 'yy/mm/dd',
beforeShowDay: highlightDays,
onSelect: function(dateText, inst) {
$("#showdaybtn").addClass("fcurrent");
$("#showweekbtn").removeClass("fcurrent");
$("#showmonthbtn").removeClass("fcurrent");
$('#type').val('1');
var p = $("#gridcontainer").swtichView("day").BcalGetOp();
if (p && p.datestrshow) {
$("#txtdatetimeshow").text(dateText);
$("#hdnTempData").val(dateText);
}
showhideToday('day');
glbView = "day";
}
});
function highlightDays(date) {
if (date >= date1 && date <= date2) {
return [true, 'highlight', 'tooltipText'];
}
return [true, ''];
}
});
});
//to check if the hidden value changed
$(document).on('change', '#dates', function () {
$( "#datepicker" ).datepicker( "refresh" );
});

Categories