jquery ui datepicker with range selection - javascript

I want to use jQuery UI datepicker on my asp.net aspx page. I want to select a range and a OK button on the jQuery UI calendar. I found a link as well where this is done:
jQuery UI Datepicker - Range Selection with Only One Control
But when I use the code on this page and click the textbox, almost 4 calendar's appear horizontally plus styles are messed up. I am not sure which files are required for this page and which ones are extra.
Please suggest how to use jQuery UI datepicker like this.

Starting from the provided link, I build up a jsfiddle with the relevant code. I can't see the issue you are facing.
Code:
$.datepicker._defaults.onAfterUpdate = null;
var datepicker__updateDatepicker = $.datepicker._updateDatepicker;
$.datepicker._updateDatepicker = function (inst) {
datepicker__updateDatepicker.call(this, inst);
var onAfterUpdate = this._get(inst, 'onAfterUpdate');
if (onAfterUpdate) onAfterUpdate.apply((inst.input ? inst.input[0] : null), [(inst.input ? inst.input.val() : ''), inst]);
}
$(function () {
var cur = -1,
prv = -1;
$('#jrange div')
.datepicker({
//numberOfMonths: 3,
changeMonth: true,
changeYear: true,
showButtonPanel: true,
beforeShowDay: function (date) {
return [true, ((date.getTime() >= Math.min(prv, cur) && date.getTime() <= Math.max(prv, cur)) ? 'date-range-selected' : '')];
},
onSelect: function (dateText, inst) {
var d1, d2;
prv = cur;
cur = (new Date(inst.selectedYear, inst.selectedMonth, inst.selectedDay)).getTime();
if (prv == -1 || prv == cur) {
prv = cur;
$('#jrange input').val(dateText);
} else {
d1 = $.datepicker.formatDate('mm/dd/yy', new Date(Math.min(prv, cur)), {});
d2 = $.datepicker.formatDate('mm/dd/yy', new Date(Math.max(prv, cur)), {});
$('#jrange input').val(d1 + ' - ' + d2);
}
},
onChangeMonthYear: function (year, month, inst) {
//prv = cur = -1;
},
onAfterUpdate: function (inst) {
$('<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" data-handler="hide" data-event="click">Done</button>')
.appendTo($('#jrange div .ui-datepicker-buttonpane'))
.on('click', function () {
$('#jrange div').hide();
});
}
})
.position({
my: 'left top',
at: 'left bottom',
of: $('#jrange input')
})
.hide();
$('#jrange input').on('focus', function (e) {
var v = this.value,
d;
try {
if (v.indexOf(' - ') > -1) {
d = v.split(' - ');
prv = $.datepicker.parseDate('mm/dd/yy', d[0]).getTime();
cur = $.datepicker.parseDate('mm/dd/yy', d[1]).getTime();
} else if (v.length > 0) {
prv = cur = $.datepicker.parseDate('mm/dd/yy', v).getTime();
}
} catch (e) {
cur = prv = -1;
}
if (cur > -1) $('#jrange div').datepicker('setDate', new Date(cur));
$('#jrange div').datepicker('refresh').show();
});
});
Demo: http://jsfiddle.net/IrvinDominin/LALED/

From: <input type="text" name="date_from" id="date_from" />
To: <input type="text" name="date_to" id="date_to" />
$(function() {
$("#date_from").datepicker({
changeMonth: true,
changeYear: true,
numberOfMonths: 1,
showOn: "button",
showAnim: "slideDown",
dateFormat: "yy-mm-dd",
onClose: function(selectedDate) {
$("#date_to").datepicker("option", "minDate", selectedDate);
}
});
$("#date_to").datepicker({
changeMonth: true,
changeYear: true,
numberOfMonths: 1,
showOn: "button",
showAnim: "slideDown",
dateFormat: "yy-mm-dd",
onClose: function(selectedDate) {
$("#date_from").datepicker("option", "maxDate", selectedDate);
}
});
});
Link demo: http://jsfiddle.net/wimarbueno/fpT6q/1/

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
</head>
<body>
<p>Date: <input type="text" id="datepicker"></p>
</body>
</html>
Try this.

Related

js code to select a week but it does keep it highlighted after selection

i am using this code to create a jquery ui calendar using a week selection but the problem is i am not able to keep it highlighted
https://jsfiddle.net/bpzc2qx9/
what method i am missing to add it this to it to make it work and keep it highlighted
here is my js code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Datepicker - Display inline</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
<script>
$( function() {
var $elem = $("#datepicker");
var weekCounter = 1;
var datepickerStartWeekDay = 1;
options = {
changeMonth: true,
changeYear: true,
showOtherMonths: true,
selectOtherMonths: true,
onClose: function (dateText, inst) {
weekCounter = 1;
},
onSelect: function(dateText, inst) {
if (datepickerStartWeekDay != null) {
var elem = $(this);
var date = elem.datepicker('getDate');
var curDayNum = date.getDay();
var offset;
if (curDayNum > datepickerStartWeekDay) {
offset = -(curDayNum - datepickerStartWeekDay);
}
else {
offset = -(7 - (datepickerStartWeekDay - curDayNum));
}
var wkStartDate = new Date(date.addDays(offset));
elem.val(wkStartDate);
}
},
beforeShowDay: function(date) {
var retClass;
// datepickerStartWeekDay: 0 = Sunday.. 6 = Saturday
// Set up weeks based on the start day with classes.
// week1, week2, week3, etc based on the start day of the week
if (datepickerStartWeekDay != null) {
if (date.getDay() == datepickerStartWeekDay) {
weekCounter += 1;
}
retClass = [true, 'week' + weekCounter];
}
else {
retClass = [true, ''];
}
return retClass;
},
onChangeMonthYear: function(year, month, inst) {
weekCounter = 1;
}
};
$elem.datepicker(options);
// Event to list for mouseover for week selection
$(".ui-datepicker-calendar td").on('mouseover', function (ev) {
var targetElem = $(ev.currentTarget);
targetElem.closest("tbody").find(".ui-week-hover").removeClass("ui-week-hover");
for (var i = 0; i < 8; i++) {
if (targetElem.hasClass("week" + i)) {
targetElem.closest("tbody").find(".week" + i).addClass("ui-week-hover");
continue;
}
}
});
} );
</script>
</head>
<body>
Date: <div id="datepicker"></div>
</body>
</html>
css code
.ui-week-hover a {
background-color:#eef6f9 !important;
}
and what method should i use to make that highlight feature work

Multiple months in single field - select year and month for each calendar

I have single field with date.... and I made that code:
Link to JSFiddle
But I would like to select year and month for each multiple calendar (like on the below image):
(edited in Paint):)
Is possible to get it?:)
Code here:
$("#date").datepicker({
numberOfMonths: 2,
dateFormat: 'mm.yy',
changeYear: true,
changeMonth: true,
yearRange: '-50:' + new Date().getFullYear(),
firstDay: 1,
onChangeMonthYear: function(){
setTimeout(function(){
$('<div class="ui-widget-header addon-header">Start date</div>').prependTo('.ui-datepicker-group.ui-datepicker-group-first');
$('<div class="ui-widget-header addon-header">End date</div>').prependTo('.ui-datepicker-group.ui-datepicker-group-last');
},010);
},
onSelect: function( selectedDate ) {
setTimeout(function(){
$('<div class="ui-widget-header addon-header">Start date</div>').prependTo('.ui-datepicker-group.ui-datepicker-group-first');
$('<div class="ui-widget-header addon-header">End date</div>').prependTo('.ui-datepicker-group.ui-datepicker-group-last');
},100);
if(!$(this).data().datepicker.first){
$(this).data().datepicker.inline = true
$(this).data().datepicker.first = selectedDate;
}else{
if(selectedDate > $(this).data().datepicker.first){
$(this).val($(this).data().datepicker.first+" - "+selectedDate);
}else{
$(this).val(selectedDate+" - "+$(this).data().datepicker.first);
}
$(this).data().datepicker.inline = false;
}
},
onClose:function(){
delete $(this).data().datepicker.first;
$(this).data().datepicker.inline = false;
}
})
$('#date').datepicker().bind('click', function() {
$('<div class="ui-widget-header addon-header">Start date</div>').prependTo('.ui-datepicker-group.ui-datepicker-group-first');
$('<div class="ui-widget-header addon-header">End date</div>').prependTo('.ui-datepicker-group.ui-datepicker-group-last');
});
.addon-header {
text-align: center;
padding: 6px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="date"/>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
I know, that the answer is not exactly what I needed, but I found the different way for this:
$("#date").datepicker({
dateFormat: 'mm.yy',
changeYear: true,
changeMonth: true,
showButtonPanel: true,
yearRange: '-50:' + new Date().getFullYear(),
firstDay: 1,
beforeShow: function() {
var thisfield=$(this);
setTimeout(function() {
if(!thisfield.val()) {
if(!$('.addon-header').length){
$('<div class="ui-widget-header addon-header">Start date</div>').insertBefore('table.ui-datepicker-calendar');
}
} else{
thisfield.val('');
if(!$('.addon-header').length){
$('<div class="ui-widget-header addon-header">Start date</div>').insertBefore('table.ui-datepicker-calendar');
}
}
},200);
},
onChangeMonthYear: function() {
var thisfield=$(this);
setTimeout(function() {
if(!thisfield.val() || thisfield.val().length > 12) {
if(!$('.addon-header').length){
$('<div class="ui-widget-header addon-header">Start date</div>').insertBefore('table.ui-datepicker-calendar');
}
} else{
if(!$('.addon-header').length){
$('<div class="ui-widget-header addon-header">End date</div>').insertBefore('table.ui-datepicker-calendar');
}
}
},200);
},
onSelect: function(selectedDate) {
if (!$(this).data().datepicker.first) {
$(this).data().datepicker.inline = true
$(this).data().datepicker.first = selectedDate;
setTimeout(function() {
$('<div class="ui-widget-header addon-header">End date</div>').insertBefore('table.ui-datepicker-calendar');
},200)
} else {
if (selectedDate > $(this).data().datepicker.first) {
$(this).val($(this).data().datepicker.first + " - " + selectedDate);
} else {
$(this).val(selectedDate + " - " + $(this).data().datepicker.first);
}
$(this).data().datepicker.inline = false;
}
},
onClose: function() {
delete $(this).data().datepicker.first;
$(this).data().datepicker.inline = false;
}
})
.addon-header {
text-align: center;
padding: 6px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="date"/>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
You can change year in "End date" :)

How to resize additional input in jquery ui Datepicker?

How can I set the width of dynamically added input fields which are getting values via a jQueryUI datepicker widget?
I have 2 inputs, "Calendar input" is where we are choosing date and it will be added automatically inside of our additional input via altField method (core method of datepicker). So can I dynamically resize the input make it lesser\larger?
Additional input: <input type="text" id="alternate" value="December,19 2015"><br>
Calendar input: <input type="text" id="from">
$("#from").datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 1,
altField: "#alternate",
altFormat: "MM d, yy",
onClose: function (selectedDate) {
$("#to").datepicker("option", "minDate", selectedDate);
}
});
Here is a link to the fiddle - https://jsfiddle.net/mhf7kxo4/
Here is a working fiddle of what you are looking for.
Basic input autoresize plugin ( just extended isValidWidthChange limitation of this one) :
(function($){
$.fn.autoResizeInput= function(o) {
o = $.extend({
maxWidth: 1000,
minWidth: 0,
comfortZone: 70
}, o);
this.filter('input:text').each(function(){
var minWidth = o.minWidth || $(this).width(),
val = '',
input = $(this),
testSubject = $('<tester/>').css({
position: 'absolute',
top: -9999,
left: -9999,
width: 'auto',
fontSize: input.css('fontSize'),
fontFamily: input.css('fontFamily'),
fontWeight: input.css('fontWeight'),
letterSpacing: input.css('letterSpacing'),
whiteSpace: 'nowrap'
}),
check = function() {
if (val === (val = input.val())) {return;}
// Enter new content into testSubject
var escaped = val.replace(/&/g, '&').replace(/\s/g,' ').replace(/</g, '<').replace(/>/g, '>');
testSubject.html(escaped);
// Calculate new width + whether to change
var testerWidth = testSubject.width(),
newWidth = (testerWidth + o.comfortZone) >= minWidth ? testerWidth + o.comfortZone : minWidth,
currentWidth = input.width(),
isValidWidthChange = ( (newWidth < currentWidth || newWidth > currentWidth )&& newWidth >= minWidth)
|| (newWidth > minWidth && newWidth < o.maxWidth);
// Animate width
if (isValidWidthChange) {
input.width(newWidth);
}
};
testSubject.insertAfter(input);
$(this).bind('keyup keydown blur update', check);
});
return this;
};
})(jQuery);
Just add these lines too:
$("#from")
.datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 1,
altField: "#alternate",
altFormat: "MM d, yy",
onClose: function (selectedDate) {
$("#to").datepicker("option", "minDate", selectedDate);
$("#alternate").focus().blur();
}
});
$("#alternate")
.autoResizeInput({
maxWidth: 18,
minWidth: 11,
comfortZone: 5
})
.focus()
.blur();
As you just want to do some stuff on datepicker date selection you can just add your stuff in the onClose or onSelect callback of the date picker
Example:
$("#from").datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 1,
altField: "#alternate",
altFormat: "MM d, yy",
onClose: function (selectedDate) {
// do you stuff over here
$("#alternate").width(100).removeClass("disabled");
$("#to").datepicker("option", "minDate", selectedDate);
}
});
Do you mean like this?
$("#from").datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 1,
altField: "#alternate",
altFormat: "MM d, yy",
onClose: function (selectedDate) {
$("#to").datepicker("option", "minDate", selectedDate);
$('input').css('width','auto');
}
});
jsFiddle Demo
If you do not wish to use a plugin, you might wish to see this solution:
Adjust width of input field to its input

appending divs dynamically based on daterange with javascript/jquery

Check here: http://js.do/code/79682
I am trying to figure out how to make it so that, when the date range is selected, the Dates that appear below are clickable and when they are clicked a div appears with the content for that date. So if Total Days: 5 then those 5 dates appear as links, when they are clicked the div content is displayed and if another div is clicked then the previous div closes and the new div content displays for the selected date. Every time I try incorporating the div "dates" it breaks the script.
The problem that you are probably running into is that you are trying to set onclick event to something that doesn't exist, that's why you need to set .delegate(). The fix is at the bottom.
So try this:
$(document).ready(function() {
document.getElementById('dates').style.display = 'none';
$( "#from" ).datepicker({
altField: "#alternate",
altFormat: "DD, d MM, yy",
minDate: null,
maxDate: "+60D",
onSelect: function(selected) {
$("#to").datepicker("option","minDate", selected);
calcDiff();
}
});
$( "#to" ).datepicker({
altField: "#alternate1",
altFormat: "DD, d MM, yy",
minDate: new Date( (new Date()).getTime() + 86400000 ),
maxDate:"+60D",
onSelect: function(selected) {
$("#from").datepicker("option","maxDate", selected);
calcDiff();
}
});
function calcDiff() {
var date1 = $('#from').datepicker('getDate');
var date2 = $('#to').datepicker('getDate');
var diff = 0;
$('#totaldays').empty();
if (date1 && date2) {
diff = (Math.floor((date2.getTime() - date1.getTime()) / 86400000))+1;
for(var d = date1.getTime(); d <= date2.getTime(); d = d + 86400000){
$('#totaldays').append( '<a class="dates">' + $.datepicker.formatDate( "MM d, yy", new Date(d) ) + "</a><br>");
}
}
$('#calculated').val(diff);
}
var tempDate;
var closed;
$('body').delegate('.dates', 'click', function() {
var date = $(this).text();
$(".createdDiv").remove();
if(date != tempDate || closed){
$(this).after( '<div class="createdDiv" style="height:100px;background-color:blue;"></div>' );
closed = false;
}
else{
closed = true;
}
tempDate = $(this).text();
});
});

Datepicker jQuery not working in IE 7

I am using this code:
<script type="text/javascript">
$(document).ready(function () {
var selector = function (dateStr) {
var d1 = $('.fromdate').datepicker('getDate');
var d2 = $('.todate').datepicker('getDate');
$('.fromdate').datepicker("option", "maxDate",d2);
$('.todate').datepicker("option", "minDate",d1);
var diff = 1;
if (d1 && d2) {
diff = diff + Math.ceil((d2.getTime() - d1.getTime()) / 86400000);
}
$('.calculated').val(diff);
$('.minim').val(d1)
}
$('.fromdate').datepicker({
showOn: "button",
buttonImage: "images/calendar_year.png",
buttonImageOnly: true,
dateFormat : 'yy-mm-dd',
changeMonth: true,
changeYear: true,
minDate: 0
});
$('.todate').datepicker({
showOn: "button",
buttonImage: "images/calendar_year.png",
buttonImageOnly: true,
dateFormat : 'yy-mm-dd',
changeMonth: true,
changeYear: true,
minDate: ($(".fromdate").is(":visible") && $(".todate").html() != ""? $('.todate').datepicker('getDate'): 'null'),
});
$('.fromdate,.todate').change(selector)
});
</script>
It worked nice but yesterday I got a call from somebody saying that it is not working in IE 7. I found two symptoms:
- any parameters makes the calendar to not appear. It works only like this
$('.fromdate').datepicker({
});
Thank you!
Try this : use index 0 for all class selector for minDate value as it returns array. And remove last comma.
$('.todate').datepicker({
showOn: "button",
buttonImage: "images/calendar_year.png",
buttonImageOnly: true,
dateFormat : 'yy-mm-dd',
changeMonth: true,
changeYear: true,
minDate: ($(".fromdate:first").is(":visible") && $(".todate:first").html() != ""? $('.todate:first').datepicker('getDate'): 'null')
});

Categories