How to stop user entering date in jQuery - javascript

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

Related

Textbox onChange event and Datepicker onSelect conflict

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"/>

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

How do I get the difference between 2 dates? jquery datepicker

I am trying to calculate the total days between selected #from day and #to day, using jquery datepicker
"I have read a lot of asked questions before writing this so I am just asking why the following code doesn't work.."
this is the code:
$(function() {
$( "#from" ).datepicker({
numberOfMonths: 1,
minDate:0,
dateFormat: 'dd-mm-yy',
onClose: function( selectedDate ) {
$( "#to" ).datepicker( "option", "minDate", selectedDate );
$("input[name='to']").val(selectedDate);
var dayFrom = selectedDate; /* Selected From Date */
}
});
$( "#to" ).datepicker({
defaultDate: "+1w",
numberOfMonths: 1,
minDate:0,
dateFormat: 'dd-mm-yy',
onClose: function( selectedDate ) {
$( "#from" ).datepicker( "option", "maxDate", selectedDate );
var dayTo = selectedDate; /* Selected To Date */
$(dayFrom, dayTo).change(function(){
if($(dayFrom).val() && $(dayTo).val()){
var startDate = parseDate($(dayFrom).val());
var endDate = parseDate($(dayTo).val());
var days = calcDaysBetween(startDate, endDate);
var price = calcPrice(days);
$('#finalDagen').html(days);
}
});
function parseDate(s){
var parts = s.split('/');
return new Date(parts[2], parts[0]-1, parts[1]);
}
function calcDaysBetween(startDate, endDate){
return (endDate-startDate)/(1000*60*60*24);
}
}
});
});
Observations
The change handler should be registered to the from and to elements, not to the variables holding the values
use the widget method getDate() to fetch the date value of the widget
The change event should be registered in the dom ready handler - not inside the onClose method
It should be
jQuery(function ($) {
var $from = $("#from"),
$to = $("#to");
$from.datepicker({
numberOfMonths: 1,
minDate: 0,
dateFormat: 'dd-mm-yy',
onClose: function (selectedDate) {
$to.datepicker("option", "minDate", selectedDate);
}
});
$to.datepicker({
defaultDate: "+1w",
numberOfMonths: 1,
minDate: 0,
dateFormat: 'dd-mm-yy',
onClose: function (selectedDate) {
$from.datepicker("option", "maxDate", selectedDate);
}
});
$from.add($to).change(function () {
var dayFrom = $from.datepicker('getDate');
var dayTo = $to.datepicker('getDate');
if (dayFrom && dayTo) {
var days = calcDaysBetween(dayFrom, dayTo);
$('#finalDagen').html(days);
}
});
function calcDaysBetween(startDate, endDate) {
return (endDate - startDate) / (1000 * 60 * 60 * 24);
}
});
Demo: Fiddle
Try subtracting the two:
var dayDifference = dayTo - dayFrom;

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