jQuery: beforeShowDay date format issue - javascript

I'm using the jQuery ui datepicker in combination with the isotope plugin and filter feature to filter out divs by date. For this filter feature to work the date has been converted to a string and stipped out all the zeros, e.g. 20/08/2013 would read as 2082013. I'm also using the beforeShowDay feature to highlight the relevant dates in the date picker, this is where the problem lies, in my example below as I'm using this date format 1782013 1882013 1982013 is also styling 01/08/2013 etc (as you can see in the fiddle).
jsFiddle: http://jsfiddle.net/neal_fletcher/jPzK2/1/
jQuery:
var $container = $('#block-wrap');
var $blocks = $("div.blocks", "#block-wrap");
$(function () {
var blocks = $('#block-wrap .blocks')
$('#datepicker').datepicker({
inline: true,
//nextText: '→',
//prevText: '←',
showOtherMonths: true,
//dateFormat: 'dd MM yy',
dayNamesMin: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
//showOn: "button",
//buttonImage: "img/calendar-blue.png",
//buttonImageOnly: true,
onSelect: function (dateText, inst) {
var date = new Date(dateText);
var dateValue = date.getDate().toString() + (date.getMonth() + 1).toString() + date.getFullYear().toString();
$container.isotope({
filter: '[data-value~="' + dateValue + '"]'
});
},
beforeShowDay: function(date){
var target = date.getDate().toString() + (date.getMonth() + 1).toString() + date.getFullYear().toString();
var contains = blocks.filter('[data-value*="' + target + '"]').length > 0;
return [true, contains ? 'special' : '', '']
}
});
});
$container.imagesLoaded(function () {
$container.isotope({
itemSelector: '.blocks',
animationEngine: 'css',
masonry: {
columnWidth: 5
}
});
});
var prepareData = function (howLong) {
var mode = howLong,
date = new Date(),
days = 0,
d = date.getDate(),
m = date.getMonth(),
y = date.getFullYear(),
duration = [],
durationReady = [];
if (mode === "week") {
days = 7;
} else if (mode === "month") {
days = 30;
}
for (i = 0; i < days; i++) {
// for each day create date objects in an array
duration[i] = new Date(y, m, d + i);
// convert objects into strings
// fe. 25th of May becomes '2552013'
durationReady[i] = duration[i].getDate().toString() + (duration[i].getMonth() + 1).toString() + duration[i].getFullYear().toString();
// 1. select all items which contain given date
var $applyMarkers = $('.blocks[data-value~="' + durationReady[i] + '"]')
.each(function (index, element) {
var thisElem = $(element),
thisElemAttr = thisElem.attr('data-value');
// 2. for each item which does not contain a marker yet, apply one
if (thisElemAttr.indexOf(mode.substring(0, 1)) === -1) {
thisElem.attr('data-value', (thisElemAttr += ' ' + mode));
}
});
}
};
prepareData("week");
prepareData("month");
$("#today").on("click", function () {
var date = new Date();
var dateValue = date.getDate().toString() + (date.getMonth() + 1).toString() + date.getFullYear().toString();
$('#datepicker').datepicker('setDate', date);
$container.isotope({
filter: '[data-value~="' + dateValue + '"]'
});
});
$("#week").on("click", function () {
$container.isotope({
filter: '[data-value ~="week"]'
});
});
$("#month").on("click", function () {
$container.isotope({
filter: '[data-value ~="month"]'
});
});
As you can see, all the dates in the data-value are successfully styled in the date picker, but due to the date format it's also styling the 1st — 9th August too. Is there anyway for both the filter function and beforeShowDay function to work without this problem?
& yes, changing the date format to e.g. 21082013 does solve the beforeShowDay styling issue, but breaks the filter function, they both need to work. Any suggestions would be greatly appreciated!

You are using * selector in your beforeShowDay function
('[data-value*="' + target + '"]')
That is why 1st August got styled - because it matches "2182013" value.
Change it to a words selector ~
('[data-value~="' + target + '"]')

Related

How to update a Jquery calendar with a JS variable

I am trying to implement this jQuery Calendar into my website. I've got the calendar running, and everything works.
I want to be able to alter the date in the calendar when a user pushes one of four buttons:
1 hour
Tomorrow
1 week
2 weeks
When a user pushes a button I would like the calendar to change the date accordingly. The calendar has the option called startDate that I can use for the purpose - but I can't seem to trigger it.
The content of val = f.x. 2020-03-07 10:02
$.datetimepicker.setLocale('da');
$('#datetimepicker').datetimepicker({
dayOfWeekStart: 1,
lang: 'da',
inline: true,
scrollMonth: false,
timepicker: false,
startDate: new Date(document.getElementById('timeForAlert').value),
onSelectDate: function() {
userHasChosen();
},
onSelectTime: function() {
userHasChosen();
}
});
$('#datetimepicker4').datetimepicker({
format: 'Y-d-m'
});
$('.some_class').datetimepicker();
function makeReadable(val) {
var mydate = new Date(val);
var hour = document.getElementById('hour').value;
var minute = document.getElementById('minutes').value;
var str = mydate.getFullYear() + '-' + ("0" + (mydate.getMonth() + 1)).slice(-2) + '-' + ("0" + mydate.getDate()).slice(-2) + ' ' + hour + ':' + minute + ':00';
return str;
}
function oneday(val) {
document.getElementById('datetimepicker').value = val;
document.getElementById('timeForAlert').value = makeReadable(val);
$.datetimepicker();
stopReload();
}
Found the solution asking in another forum.
The documentation for this script is terrible !
Here is what we found:
$(function() {
$('#dt').datetimepicker({
dayOfWeekStart: 1,
lang: 'da',
inline: true,
scrollMonth: false,
timepicker: false,
startDate: new Date()
});
});
$('#btn').click(function() {
$('#dt').datetimepicker({
value: new Date('2020-01-01T00:00:00Z')
});
});
Run this from a button with id = btn and you're set

How to change the format of JQuery Date Picker to MM/DD/YYYY

Based on this link
This where I will go if i wanna change my date format
defaults: {
formatDate: function(date) {
var formatted = $.datePicker.utils.pad(date.getDate(), 2) + '/' + $.datePicker.utils.pad(date.getMonth() + 1, 2) + '/' + date.getFullYear();
return formatted;
},
parseDate: function(string) {
var date = new Date();
var parts = string.match(/(\d{1,2})\/(\d{1,2})\/(\d{4})/);
if ( parts && parts.length == 4 ) {
date = new Date( parts[3], parts[2] - 1, parts[1] );
}
return date;
},
selectDate: function(date) {
return true;
},
limitCenturies: true,
closeOnPick: true,
appendTo: null
},
How can I make this to MM/DD/YYYY? I tried everything I change it but when Im selecting dates the value goes on different dates
Here is the error
According to the documentation, this should work:
defaults: {
formatDate: function(date) {
//var formatted = $.datePicker.utils.pad(date.getDate(), 2) + '/' + $.datePicker.utils.pad(date.getMonth() + 1, 2) + '/' + date.getFullYear();
var formatted = $.datePicker.utils.pad(date.getMonth() + 1, 2) + '/' + $.datePicker.utils.pad(date.getDate(), 2) + '/' + date.getFullYear();
return formatted;
},
parseDate: function(string) {
var date = new Date();
if ( string ) {
formatted_date = string.split('/');
date = new Date( formatted_date[2], formatted_date[0] - 1, formatted_date[1] );
}
return date;
},
selectDate: function(date) {
return true;
},
limitCenturies: true,
closeOnPick: true,
appendTo: null
}
See it in action: Demo.
Try this out
var date = new Date('2014-01-06');
var newDate = date.toString('dd-MM-yy');

How to get date in specific format

I want to have the dateformat in this format: 2015-08-04T00:00:00Z.
so first year, month, day.
beforeShowDay: function (date) {
var dt = $.datepicker.formatDate('yy-mm-dd', date, "getDate")
return [$('#form_one3 > option:gt(0)[value="' + dt + 'T00:00:00Z"]').length != 0];
},
onSelect: function (dateText, inst) {
var dt = $.datepicker.formatDate('yy-mm-dd', dateText, "getDate")
alert(dt);
var hallo = $("#form_inp1").val() + 'T00:00:00Z';
alert(dateText);
alert(hallo);
//$("#form_inp1").datepicker("getDate");
//alert($("#form_inp1").formatDate('yy-mm-dd', dateText, "getDate")
},
But If I do an alert(dateText) I see the format as: 4-8-2015 and it has to be: 2015-08-04.
Thank you
If I try it like this:
onSelect: function (dateText, inst) {
dateText = dateText.split("-");
dateText = new Date('' + dateText[2] + '-' + dateText[1] + '-' + dateText[0] + '');
alert(dateText);
}
I get invalid date
So this var hallo = $("#form_inp1").val() + 'T00:00:00Z';
returns: 4-8-2015T00:00:00Z . But it has to be:2015-08-04T00:00:00Z.
Thank you
Quick fix is to change the date format using plain Javascript. This can be achieved by following script.
dt= dt.split("-");
dt = new Date('' + dt[2] + '-' + dt[1] + '-' + dt[0] + '');
to add zero in case the day, month and year is below 10, use following method.
function AddTrailingZero(i) {
if (i < 10) { i = "0" + i }; // add zero in front of numbers < 10
return i;
}
Let me know if you have any question related to the code snippet above.

JQuery On event after element is changed via Javascript

I am trying to create a jquery plugin to do custom validation.
I have a jqueryUI date picker that enters a date into an input field.
I am trying to attach an on change event to the input field that gets populated by the date picker but it isn't firing. I guess because it isn't being changed by the user, it is being updated by JavaScript/jqueryUI.
My question is how can I attach an on change event to a field that is updated via JavaScript and not by the user?
my plugin code:
;(function ($, window) {
var validateStuff = function(element){
$(element).on('change', function(event){
console.log( "Handler for .on() called." );
});
};
$.fn.validate = function(options){
return this.each(function(){
var elem = $( this );
validateStuff(elem);
});
};
})(jQuery);
UPDATE:
datepicker code
$('.day-picker').datepicker({
inline: true,
showOtherMonths: true,
dayNamesMin: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
onSelect: function (dateText, inst) {
var startDate = new Date(dateText);
var selDay = startDate.getDate();
var selMonth = startDate.getMonth() + 1;
var selYear = startDate.getFullYear();
var fieldElement = $(this).siblings(".date-field");
var selDay = selDay < 10 ? "0" + selDay : selDay;
var selMonth = selMonth < 10 ? "0" + selMonth : selMonth;
$(fieldElement).val(selDay + "-" + selMonth + "-" + selYear);
}
});
When you change the value of the input element, you can trigger the change event:
$(fieldElement).val(selDay + "-" + selMonth + "-" + selYear).change();
Which can also be written as
$(fieldElement).val(selDay + "-" + selMonth + "-" + selYear).trigger('change');
Note: Event handler methods like change() will simply trigger the event if no parameters are passed.

How to get datepicker to be highlighted upon refresh

I have a datepicker that highlights a selected week. It is using an ajax request. Which is where I am having a problem. When I select a week i.e. 29/08/11 and the page refreshes the highlighted week is no longer highlighted.
Datepicker.js
$(function()
{
var startDate;
var endDate;
var selectCurrentWeek = function()
{
window.setTimeout(function () { $('.week-picker').find('.ui-datepicker-current-day a').addClass('ui-state-active')}, 1000);
}
function check(d) {
if(d.length() == 2) {
dd = d;
return dd;
} else {
dd = "0" + myDateParts[0];
return dd;
}
}
var selectedWeek;//remember which week the user selected here
$('.week-picker').datepicker( {
beforeShowDay: $.datepicker.noWeekends,
showOtherMonths: true,
selectOtherMonths: true,
onSelect: function(dateText, inst) {
var date = $(this).datepicker('getDate');
startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 1);
endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 6);
var dateFormat = 'yy-mm-dd'
var newDate = $('#startDate').text($.datepicker.formatDate( dateFormat, startDate, inst.settings ));
var oldDate = document.getElementById('startDate');
var date_textnode = oldDate.firstChild;
var date_text = date_textnode.data;
myDateParts = date_text.split("-");
var dd = myDateParts[2];
var mm = myDateParts[1];
var yy = myDateParts[0];
selectCurrentWeek();
window.location.href = "/timesheet?week_commencing=" + yy + "-" + mm + "-" + dd; <<
At this point above this is where the window is refreshed and it GETs the URL. So that when I select a date it outputs like the following http://0.0.0.0:3000/timesheet?week_commencing=2011-09-05
},
beforeShowDay: function(date) {
var cssClass = '';
if(date >= startDate && date <= endDate)
cssClass = 'ui-datepicker-current-day';
return [true, cssClass];
},
onChangeMonthYear: function(year, month, inst) {
selectCurrentWeek();
}
});
$('.week-picker .ui-datepicker-calendar tr').live('mousemove', function() { $(this).find('td a').addClass('ui-state-hover'); });
$('.week-picker .ui-datepicker-calendar tr').live('mouseleave', function() { $(this).find('td a').removeClass('ui-state-hover'); });
});
index.html.erb
window.onload = function getURL(){
var url = document.location.href;
urlSplit = url.split("/timesheet");
if(urlSplit[1]== "")
{
var d = getMonday(new Date());
dd = zeroPad(d.getDate(),2);
mm = zeroPad(d.getMonth()+1,2);
yy = d.getFullYear();
document.getElementById('startDate').innerHTML = yy + "-" + mm + "-" + dd;
//window.location.href = "/timesheet?week_commencing=" + yy + "-" + mm + "-" + dd;
}
else
{
week = url.split("week_commencing=");
//return week[1];
document.getElementById('startDate').innerHTML = week[1];
}
}
Note
The window.onload URL function gets the week commencing from the url
Jsfiddle - Including datepicker
http://jsfiddle.net/YQ2Zw/12/
Update
You can use the defaultDate to set the initial date selected on the datepicker, and simulate a click event on the calendar to highlight the week:
var selectDate = '09/29/2011';
$('.week-picker').datepicker({
defaultDate: selectDate
}).click(function(event) {
// highlight the TR
$(".ui-datepicker-current-day").parent().addClass('highlight');
// highlight the TD > A
$(".ui-datepicker-current-day:eq(0)").siblings().find('a').addClass('white');
}).click();
Example: http://jsfiddle.net/william/YQ2Zw/15/
Update
Assuming Datepicker.js is loaded in timesheet, you should be able to do that with two more lines:
window.onload = function getURL(){
var url = document.location.href;
urlSplit = url.split("/timesheet");
if(urlSplit[1]== "")
{
var d = getMonday(new Date());
dd = zeroPad(d.getDate(),2);
mm = zeroPad(d.getMonth()+1,2);
yy = d.getFullYear();
document.getElementById('startDate').innerHTML = yy + "-" + mm + "-" + dd;
//window.location.href = "/timesheet?week_commencing=" + yy + "-" + mm + "-" + dd;
$('.week-picker').datepicker({
defaultDate: mm + '/' + dd + '/' + yy
}).click();
}
else
{
week = url.split("week_commencing=");
//return week[1];
document.getElementById('startDate').innerHTML = week[1];
}
}

Categories