Textbox onChange event and Datepicker onSelect conflict - javascript

I have two text boxes for date fields. User is allowed to enter date in those fields via both jQuery-ui Datepicker and via manually typing through keyboard. The requirement is after entering date in the 1st textbox, the second textbox should get populated with the date exactly 1 year later.I have handled most of the scenarios.
I will try to explain clearly in which scenario I am facing the issue. Suppose I am typing in the date manually from keyboard and suddenly I decide to select a different date from Datepicker instead. In this case the the textbox is not showing the selected date from datepicker. I hope I am able to articulate clearly. My guess is Datepicker's onSelect() event is not getting fired in this particular scenario because of any conflict with the textbox's onChange() event.
$('#datepicker1').datepicker({
constrainInput: "true",
dateFormat: "mm/dd/yy",
changeMonth: true,
changeYear: true,
onSelect: function (date) {
var parsedDate = parseDate(date);
var moddate = new Date(Date.parse(parsedDate));
moddate.setFullYear(moddate.getFullYear() + 1);
var newDate = moddate.toDateString();
newDate = new Date(Date.parse(newDate));
$("#datepicker2").datepicker("option", "maxDate", newDate);
$('#datepicker2').datepicker('setDate', newDate);
}
});
$('#datepicker2').datepicker({
dateFormat: "mm/dd/yy",
changeMonth: true,
changeYear: true,
});
var maskConfig = {
leapday: "29-02-",
separator: "/",
showMaskOnHover: false,
showMaskOnFocus: false,
placeholder: "00/00/0000"
}
$('#datepicker1').inputmask('mm/dd/yyyy', maskConfig);
$('#datepicker2').inputmask('mm/dd/yyyy', maskConfig);
$('#datepicker1').on("change",function () {
var parsedDate = parseDate($('#datepicker1').val());
var date = new Date(Date.parse(parsedDate));
date.setFullYear(date.getFullYear() + 1);
var newDate = date.toDateString();
newDate = new Date(Date.parse(newDate));
$("#datepicker2").datepicker("option", "maxDate", newDate);
$('#datepicker2').datepicker('setDate', newDate);
});
function parseDate(input) {
var parts = input.split('/');
return new Date(parts[2], parts[0] - 1, parts[1]);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.3.4/jquery.inputmask.bundle.min.js"></script>
<input type="text" id="datepicker1"/>
<input type="text" id="datepicker2"/>

I couldn't find any exact fix for this issue. I am currently going with a small hack/workaround. I am hiding the datepicker as soon as user starts typing inside the textbox. I am using the "keyup" event handler.
$('#datepicker1').datepicker({
constrainInput: "true",
dateFormat: "mm/dd/yy",
changeMonth: true,
changeYear: true,
onSelect: function (date) {
var parsedDate = parseDate(date);
var moddate = new Date(Date.parse(parsedDate));
moddate.setFullYear(moddate.getFullYear() + 1);
var newDate = moddate.toDateString();
newDate = new Date(Date.parse(newDate));
$("#datepicker2").datepicker("option", "maxDate", newDate);
$('#datepicker2').datepicker('setDate', newDate);
}
});
$('#datepicker2').datepicker({
dateFormat: "mm/dd/yy",
changeMonth: true,
changeYear: true,
});
var maskConfig = {
leapday: "29-02-",
separator: "/",
showMaskOnHover: false,
showMaskOnFocus: false,
placeholder: "00/00/0000"
}
$('#datepicker1').inputmask('mm/dd/yyyy', maskConfig);
$('#datepicker2').inputmask('mm/dd/yyyy', maskConfig);
$('#datepicker1').on("change",function () {
var parsedDate = parseDate($('#datepicker1').val());
var date = new Date(Date.parse(parsedDate));
date.setFullYear(date.getFullYear() + 1);
var newDate = date.toDateString();
newDate = new Date(Date.parse(newDate));
$("#datepicker2").datepicker("option", "maxDate", newDate);
$('#datepicker2').datepicker('setDate', newDate);
});
$('#datepicker1').on('keyup', function() {
if (this.value.length > 0) {
$('#datepicker1').datepicker('hide') ;
}
else{
$('#datepicker1').datepicker('show') ;
}
});
$('#datepicker2').on('keyup', function() {
if (this.value.length > 0) {
$('#datepicker2').datepicker('hide') ;
}
else{
$('#datepicker2').datepicker('show') ;
}
});
function parseDate(input) {
var parts = input.split('/');
return new Date(parts[2], parts[0] - 1, parts[1]);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.3.4/jquery.inputmask.bundle.min.js"></script>
<input type="text" id="datepicker1"/>
<input type="text" id="datepicker2"/>

Related

How to stop user entering date in jQuery

I am trying to stop user from entering back date than the first one and i am unable to do that
$(document).ready(function() {
$("#date_rash_onset").datepicker({
todayBtn: 1,
autoclose: true,
format: 'dd-mm-yyyy',
}).on('changeDate', function(selected) {
var minDate = new Date(selected.date.valueOf());
$('#date_investigation').datepicker('setStartDate', minDate);
$('#date_collection').datepicker('setStartDate', minDate);
});
$("#date_investigation").datepicker({
format: 'dd-mm-yyyy'
}).on('changeDate', function(selected) {
var minDate = new Date(selected.date.valueOf());
$('#date_rash_onset').datepicker('setEndDate', minDate);
$('#date_date_onset').datepicker('endDate', '+0d');
});
});
function fromDate(start_date_id, end_date_id){
var from_date = $('#'+start_date_id).datepicker({ dateFormat: 'dd-mm-yyyy' }).val();
var to_date = $("#"+end_date_id).datepicker({ dateFormat: 'dd-mm-yyyy' }).val();
$("#"+end_date_id).datepicker('setStartDate', from_date);
$("#"+end_date_id).datepicker('setEndDate', '+2y');
if(to_date < from_date){
$("#"+end_date_id).val('');
}
}
function toDate(start_date_id, end_date_id){
$('#'+start_date_id).datepicker('setStartDate', "01-01-1925");
$('#'+start_date_id).datepicker('setEndDate', '+0d');
}
$("#date_rash_onset").on( "change", function() {
fromDate('date_rash_onset', 'date_collection');
});
$("#date_collection").on( "change", function() {
toDate('date_rash_onset', 'date_collection');
});

Need some help for this JavaScript code for DatePicker

here is my code :
$(function() {
$('#startDate').datepicker({
dateFormat: "dd/mm/yy",
changeMonth: true,
changeYear: true,
showButtonPanel: true,
onClose: function(dateText, inst) {
function isDonePressed() {
return ($('#ui-datepicker-div').html().indexOf('ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all ui-state-hover') > -1);
}
if (isDonePressed()) {
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
$(this).datepicker('setDate', new Date(year, month, 1)).trigger('change');
$('.date-picker').focusout()
}
},
beforeShow: function(input, inst) {
inst.dpDiv.addClass('month_year_datepicker')
if ((datestr = $(this).val()).length > 0) {
year = datestr.substring(datestr.length - 4, datestr.length);
month = datestr.substring(0, 2);
$(this).datepicker('option', 'defaultDate', new Date(year, month - 1, 1));
$(this).datepicker('setDate', new Date(year, month - 1, 1));
$(".ui-datepicker-calendar").hide();
}
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.0/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.0/jquery-ui.min.js"></script>
<input id="startDate" />
The problem is I don't know why the date changes to first day of the year when I focusout and come back to it. If you found the error in the code please let me know.
jsfiddle
I find the error thanks for the help #depperm it was in this part
month = datestr.substring(0, 2);
corrected to
month = datestr.substring(3, 5);

jQuery Calender UI datepicker doesn't work when we click ESC key, calendar not working after 1st click on IE and Safari

When I click first on JQuery calendar it will display the calendar and if i select date it works smoothly. But When I press the Esc after displaying calendar instead of selecting date, it disappears but I cant get click next time onward.
It works fine in Chrome and Firefox but IE and Safari I cant click second time if i click on ESC after click on first time.
Is there anyone faced this problem? or any solution can suggest for this.
I am using jquery-ui-calendar as below details.
/*! jQuery UI - v1.11.4 - 2016-06-30
* http://jqueryui.com
* Includes: core.js, datepicker.js
* Copyright jQuery Foundation and other contributors; Licensed MIT */
Below is my JS code:
/* This Section Custom Calendar*/
$(document).ready(function() {
// jquery date picker
$(function () {
if ($(window).width() < 768) {
$.datepicker.setDefaults({
changeMonth: false,
changeYear: false,
dateFormat: customFormat(),
defaultDate: +0,
minDate: 0,
maxDate: '+364d',
numberOfMonths: 1,
showAnim: 'fadeIn',
showButtonPanel: true
});
}
else {
// Set default datepicker options
$.datepicker.setDefaults({
changeMonth: false,
changeYear: false,
dateFormat: customFormat(),
defaultDate: +0,
minDate: 2,
maxDate: '+364d',
numberOfMonths: 2,
showAnim: 'fadeIn',
showButtonPanel: true
});
}
// Calendar 1
$(function () {
$(function () {
$('#arrivaldate').datepicker({
onSelect: function (dateText, instance) {
var arrivaldateold = CleanDate($("#arrivaldate").val());
var arrdatenew = $.datepicker.parseDate(customFormat(), arrivaldateold);
var arrday = arrdatenew.getDate();
var arrmon = (arrdatenew.getMonth() + 1);
var arrYear = arrdatenew.getFullYear()
if (arrday.toString().length==1){arrday="0"+arrday;}
if (arrmon.toString().length==1){arrmon="0"+arrmon;}
var arrivaldatenew = arrday + "/" + arrmon + "/" + arrYear;
$("#calendararr").val(arrivaldatenew);
// Populate checkout date field
var nextDayDate = $('#arrivaldate').datepicker('getDate', '+3d');
nextDayDate.setDate(nextDayDate.getDate() + 1);
$("#arrivaldate").val(FormatDate(arrivaldatenew));
$('#depaturedate').datepicker('setDate',nextDayDate );
$("#depaturedate").val(ChangeDateFormat(nextDayDate));
},
onClose: function () {
$("#depaturedate").datepicker("show");
}
});
});
// Set checkout datepicker options
$(function () {
$('#depaturedate').datepicker({
// Prevent selecting checkout date before arrival:
beforeShow: customRange
});
});
function customRange(a) {
var deptdateold = CleanDate($("#depaturedate").val());
var deptdatenew = $.datepicker.parseDate(customFormat(), deptdateold);
var dptday = deptdatenew.getDate();
var dptmon = (deptdatenew.getMonth() + 1);
var dptYear = deptdatenew.getFullYear()
if (dptday.toString().length==1){dptday="0"+dptday;}
if (dptmon.toString().length==1){dptmon="0"+dptmon;}
var departuredatenew = dptday + "/" + dptmon + "/" + dptYear;
$("#calendardept").val(departuredatenew);
// changes done by parul starts for 30 days limit
var SelectedDate = CleanDate($("#arrivaldate").val());
var date1 = $.datepicker.parseDate(customFormat(), SelectedDate);
var d = new Date();
var diff = date1 - d;
diff = (diff / (1000 * 3600 * 24));
var maxdiff = parseInt(diff);
maxdiff = maxdiff + 31;
var b = new Date();
var c = new Date(b.getFullYear(), b.getMonth(), b.getDate());
if (a.id == 'depaturedate') {
if ($('#arrivaldate').datepicker('getDate') != null) {
//c = $('#arrivaldate').datepicker('getDate', '+3d');
b = CleanDate($("#arrivaldate").val());
c = $.datepicker.parseDate(customFormat(), b);
c.setDate(c.getDate() + 1);
}
}
return {
minDate: c,
maxDate: maxdiff + "d"
} // changes done by parul ends
}
});
$("#depaturedate").change(function () {
var deptdateold = CleanDate($("#depaturedate").val());
var deptdatenew = $.datepicker.parseDate(customFormat(), deptdateold);
var dptday = deptdatenew.getDate();
var dptmon = (deptdatenew.getMonth() + 1);
var dptYear = deptdatenew.getFullYear()
if (dptday.toString().length==1){dptday="0"+dptday;}
if (dptmon.toString().length==1){dptmon="0"+dptmon;}
var departuredatenew = dptday + "/" + dptmon + "/" + dptYear;
$("#calendardept").val(departuredatenew);
$("#depaturedate").val(ChangeDateFormat(deptdatenew));
});
$( "#c_checkout" ).click(function() {
$("#depaturedate").datepicker("show");
});
$( "#c_checkin" ).click(function() {
$("#arrivaldate").datepicker("show");
});
});
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 2);
var tomorrow = new Date(tomorrow).toLocaleDateString('en-GB',
{
day : 'numeric',month : 'short', year : 'numeric'
}).split(' ').join(' ');
$('#arrivaldate').val(tomorrow);
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 3);
var tomorrow = new Date(tomorrow).toLocaleDateString('en-GB',
{
day : 'numeric',month : 'short', year : 'numeric'
}).split(' ').join(' ');
$('#depaturedate').val(tomorrow);
}); //JQuery Document Ready Section Finished Here

Button to increase date in text box

I am writing following code.
<!doctype html>
<html><head>
<meta charset="utf-8" />
<title>jQuery UI Datepicker - Icon trigger</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js">
</script> <script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js">
</script>
<script>
$(function () {
$("#datepicker").datepicker({
minDate: -0,
maxDate: "+1M +2D",
showOn: "button",
buttonImage: "calendar.png",
buttonImageOnly: true,
dateFormat: 'D dd MM yy' });
$.datepicker.formatDate('yy-mm-dd');
});
function updateDate(){
var inputDate=document.getElementById('datepicker').value;
var selectedDate=new Date(inputDate);
var today=new Date();
var tomorrow=new Date();
tomorrow.setDate(today.getDate()+1);
selectedDate.setHours(0,0,0,0);
today.setHours(0,0,0,0);
tomorrow.setHours(0,0,0,0);
var DaysFull=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];
var DaysShort=["Sun","Mon","Tue","Wed","Thu","Fri","Sat","Sun"];
var MonthsFull=["January","February","March","April","May","June","July","August","September","October","November","December","January"];
var MonthsShort=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","Jan"];
var finalDate=DaysShort[selectedDate.getDay()]+" "+selectedDate.getDate()+" "+MonthsFull[selectedDate.getMonth()];
if(selectedDate.getTime() == today.getTime()){
document.getElementById('datepicker').value=finalDate+" (Today)";
}
else if(selectedDate.getTime() == tomorrow.getTime()){document.getElementById('datepicker').value=finalDate+" (Tomorrow)";}
else {document.getElementById('datepicker').value=finalDate;}
}
function addDaysToDate() {
var date1= document.getElementById('datepicker').value;
var date = new Date( Date.parse( date1 ) );
date.setDate( date.getDate() + 1 );
alert(date);
document.getElementById('datepicker').value=date;
}
</script>
</head>
<body>
<form><input type="text" id="datepicker" onchange="javascript:updateDate()" style="width:160px" />
<button onclick="addDaysToDate()">add</button></form>
</body></html>
I have a button on click of which date in text box should be increase by 1 upto next 32 days and not beyong but above code increases the date and value disappears from the text box rather than showing ...
You are setting a date field to set additional text so the date in not a valid date object and break the plugin.
You are using the datepicker plugin so you can use getDate and setDate methods to get/set the values as date objects.
Docs: http://api.jqueryui.com/datepicker/#method-getDate and http://api.jqueryui.com/datepicker/#method-setDate
I changed your code by using an additional field to show if the date is today or tomorrow:
$(function () {
$("#datepicker").datepicker({
minDate: -0,
maxDate: "+1M +2D",
showOn: "button",
buttonImage: "calendar.png",
buttonImageOnly: true,
dateFormat: 'D dd MM yy'
});
$("#datepicker").change(function () {
updateDate();
});
$("#addDate").click(function () {
addDaysToDate();
});
});
function updateDate() {
var today = new Date();
var tomorrow = new Date();
tomorrow.setDate(today.getDate() + 1);
var date2 = $('#datepicker').datepicker('getDate');
date2.setHours(0,0,0,0);
today.setHours(0,0,0,0);
tomorrow.setHours(0,0,0,0);
if (date2.getTime() == today.getTime()) {
$('#todtom').text(" (Today)");
} else if (date2.getTime() == tomorrow.getTime()) {
$('#todtom').text(" (Tomorrow)");
} else {
$('#todtom').text("");
}
}
function addDaysToDate() {
var date2 = $('#datepicker').datepicker('getDate');
date2.setDate(date2.getDate() + 1);
$('#datepicker').datepicker('setDate', date2);
$('#datepicker').change();
}
I changed the code to use full jQuery code not a mix of jQuery and JS for DOM manipulation.
Demo:

jQuery datepicker not selectable anymore

I have a jQuery datepicker that used to be working very well. However, since yesterday, I must have changed something. When I hover over the calendar, nothing happens. When I click on the calendar, nothing works. But, I am able to change the behaviour of the calendar via code. As you can see, I was able to remove the prev and next buttons in the first calendar. Is there anything I forgot to check? Why can I not select any date of the calendar anymore? Any hint is appreciated. Btw, I checked the code on JSFiddle, and there it is working :(
This is my JavaScript:
$(function() {
var startDate;
var endDate;
var selectCurrentWeek = function() {
window.setTimeout(function () {
$('#datepicker').find('.ui-datepicker-current-day tr').addClass('ui-state-hover');
$('#datepicker').find('.ui-datepicker-next').remove();
$('#datepicker').find('.ui-datepicker-prev').remove();
}, 1);
}
$('#datepicker').datepicker( {
showOtherMonths: true,
selectOtherMonths: false,
onSelect: function(dateText, inst) {
var date = $(this).datepicker('getDate');
startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 6);
$('#calendar').weekCalendar('gotoWeek', date);
selectCurrentWeek();
},
beforeShowDay: function(date) {
var cssClass = '';
if(date >= startDate && date <= endDate)
cssClass = 'ui-datepicker-current-day';
return [true, cssClass];
},
onChangeMonthYear: function(year, month, inst) {
selectCurrentWeek();
}
});
$('#datepicker' ).datepicker( "option", $.datepicker.regional[ 'de' ] );
$('#datepicker').find('.ui-datepicker-next').remove();
$('#datepicker').find('.ui-datepicker-prev').remove();
$('#datepicker .ui-datepicker-calendar tr').live('mousemove', function() { $(this).find('td a').addClass('ui-state-hover'); });
$('#datepicker .ui-datepicker-calendar tr').live('mouseleave', function() { $(this).find('td a').removeClass('ui-state-hover'); });
// handling datepicker classes
var startDate;
var endDate;
var selectCurrentWeek_next = function() {
window.setTimeout(function () {
}, 1);
}
$('#datepicker_next_month').datepicker( {
showOtherMonths: true,
selectOtherMonths: true,
onSelect: function(dateText, inst) {
var date = $(this).datepicker('getDate');
$('#calendar').weekCalendar('gotoWeek', date);
selectCurrentWeek_next();
},
beforeShowDay: function(date) {
var cssClass = '';
return [true, cssClass];
},
onChangeMonthYear: function(year, month, inst) {
selectCurrentWeek_next();
}
});
$('#datepicker_next_month' ).datepicker( "option", $.datepicker.regional[ 'de' ] );
$('#datepicker_next_month' ).datepicker().datepicker('setDate','+1m');
$('#datepicker_next_month .ui-datepicker-calendar tr').live('mousemove', function() { $(this).find('td a').addClass('ui-state-hover'); });
$('#datepicker_next_month .ui-datepicker-calendar tr').live('mouseleave', function() { $(this).find('td a').removeClass('ui-state-hover'); });
});
This is the relevant HTML part:
<div id="datepicker"></div>
<div id="datepicker_next_month"></div>
These are the scripts I import:
<script type='text/javascript' src='libs/jquery-1.4.4.min.js'></script>
<script type='text/javascript' src='libs/jquery-ui-1.8.11.custom.min.js'></script>
<script type='text/javascript' src='libs/jquery-ui-i18n.js'></script>
Here is an image of the calendar:
I finally found the problem. I used Google Chroms Element inspector and discovered, that another div was overlaying the datepicker divs. After fixing that problem, everything works again :)

Categories

Resources