How to update a Jquery calendar with a JS variable - javascript

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

Related

How can I change my API link with a date picker

Currently my api link is dynamic by selecting the current year and month.
Example:
APILINK.../202109
That part is fine... But what I want to do is change the last part of the API link (Year and Month) with a datepicker and I'm not sure how I can do that.
My current Code:
const timehsheetUrl = "API LINK"
const today = new Date();
const date = today.getFullYear()+('0' + (today.getMonth() + 1)).slice(-2);
const settings = {
"async": true,
"crossDomain": true,
"url": timesleetUrl + date,
"method": "GET",
"headers": {}
}
No, you don't need to use datepicker plugin, while plugin is more convenient.
Here's an example with default HTML date-input.
const timesleetUrl = "API LINK";
const today = new Date();
function urlDateSuffix(_date) {
return _date.getFullYear()+('0' + (_date.getMonth() + 1)).slice(-2);
}
let settings = {
"async": true,
"crossDomain": true,
"url": timesleetUrl + urlDateSuffix(today),
"method": "GET",
"headers": {}
}
console.log(settings);
$(function() {
$('#datepicker').change(function() {
settings.url = timesleetUrl + urlDateSuffix(new Date(this.value));
console.log(settings);
alert(settings.url);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="date" id="datepicker">
It's easy use jQuery date picker.
On date select script should return selected date's month and year.
Store the output in variable and format. The code shown below will help you
// html markup, use jQuery UI CDN in head section
<input type="text" id="calendar" name="date1"/>
// html markup
<script>
$('#calendar').datepicker({
dateFormat: 'yy-m-d',
inline: true,
onSelect: function(dateText, inst) {
var date = $(this).datepicker('getDate'),
day = date.getDate(),
month = date.getMonth() + 1,
year = date.getFullYear();
// alert(day + '-' + month + '-' + year);
// this is your result
alert( "api link is "+"APILINK.../"+year+month);
}
});
</script>

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

jQuery: beforeShowDay date format issue

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 + '"]')

jquery datepicker beforeShowDay works for wrong month?

I'm using jquery's datepicker to select dates and I want to highlight some dates - but I'm experiencing a strange problem with beforeShowDay.
When the page loads it seems that the json data is loaded, but when I click into the input box and datepicker appears, nothing is highlighted. After I click on forward month or backward, data from a previous month is loaded (e.g. click in input -> datepicker appears -> no highlights -> click on next month -> data from prev month appears highlighted)...
I've googled a long time now, checked if data is loaded before everything, but somehow this behaviour is not changing. Both datepicker experience the same problem.
(jquery-ui datepicker 1.10.1, jquery 1.9.1)
I'm glad about every hint!
var resDates;
var done = false;
function markDate(date) {
var ret = [true, 'free'];
if (!done) {
$.ajax({
dataType: "json",
url: "modules/OutShop/getReservations.php",
data: {item_id: $("#item-id").val()},
async: false,
success: function (dates) {
resDates = dates;
done = true;
}
});
}
$.each(resDates, function(key, value) {
var d = (date.getFullYear() + "-" + ("0" + date.getMonth()).slice(-2) + "-" + ("0" + date.getDate()).slice(-2));
if (d == value["day"]) {
//$("body").append("d: " + d + ", v: " + value["day"] + ", s: " + value["status"] + " ");
//$("body").append("s: " + value["status"] + " ");
if (value["status"] == "1")
ret = [false, 'marked'];
else if (value["status"] == "2")
ret = [false, 'reserved'];
else
ret = [true, 'free'];
}
});
return ret;
}
$(document).ready(function() {
if (!done) {
$.ajax({
dataType: "json",
url: "modules/OutShop/getReservations.php",
data: {item_id: $("#item-id").val()},
async: false,
success: function (dates) {
resDates = dates;
//done = true;
}
});
}
$("#item-datepicker-min").datepicker({
showButtonPanel: true,
defaultDate: +3,
minDate: +3,
beforeShowDay: markDate,
onSelect: function(selectedDate) {
$("#item-datepicker-max").datepicker("option", "minDate", selectedDate);
}
});
$("#item-datepicker-max").datepicker({
showButtonPanel: true,
minDate: +3,
defaultDate: +6,
beforeShowDay: markDate,
onSelect: function(selectedDate) {
$("#item-datepicker-min").datepicker("option", "maxDate", selectedDate);
}
});
});
EDIT
For further information: This is an example json object I got from the ajax response.
[{"status":3,"day":"2013-04-10"},{"status":3,"day":"2013-04-11"},{"status":3,"day":"2013-04-12"},{"status":3,"day":"2013-04-13"},{"status":2,"day":"2013-04-10"},{"status":2,"day":"2013-04-11"},{"status":2,"day":"2013-04-12"},{"status":2,"day":"2013-04-13"}]
Looks like your months are offset by 1, the javascript method date.getMonth() returns the months zero-based (eg. January is 0, Feb is 1) and your PHP script returns the date in normal format (Jan is 1, Feb is 2)
Check this
So if you change
var d = (date.getFullYear() + "-" + ("0" + date.getMonth()).slice(-2) + "-" + ("0" + date.getDate()).slice(-2));
to
var d = (date.getFullYear() + "-" + ("0" + date.getMonth()+1).slice(-2) + "-" + ("0" + date.getDate()).slice(-2));
you should get the right month showing

Unexpected Identifier Syntax Error in Javascript

I get an Unxepected Identifier editor with the following code. I've been troubleshooting it all day, and nothing. Hoping a fresh pair of eyes can spot my error. I'm trying to use jQuery UI to set up a date-picker and then get and manipulate the date. Changing the date on the picker should change an image on the page associated with that date via ajax.
$(document).ready(function(){
// Datepicker
$('#datepicker').datepicker({
dateFormat: 'yy-mm-dd',
inline: true,
minDate: new Date(2012, 06 - 1, 1),
maxDate:new Date(2012, 09 - 1, 31),
onSelect: function(){
var day1 = ($("#datepicker").datepicker('getDate').getDate()).toString().replace(/(^.$)/,"0$1");
var month1 = ($("#datepicker").datepicker('getDate').getMonth() + 1).toString().replace(/(^.$)/,"0$1");
var year1 = $("#datepicker").datepicker('getDate').getFullYear();
var fullDate = year1 + "/" + month1 + "/" + day1;
var dashDate = year1 + "-" + month1 + "-" + day1;
var str_output = "<a id=\"single_image\" href=\"http://www.lasalle.edu/150/dayinhistory/" + fullDate + ".jpg\" title=\"\"><img src=\"http://www.lasalle.edu/scripts/timthumb/timthumb.php?src=http://www.lasalle.edu/150/dayinhistory/" + fullDate + ".jpg&w=560&h=350&zc=1&a=t\">";
$('#this-day-photo-archive').html(str_output);
var data = 'day=' + dashDate;
$.ajax({
url: 'http://www.lasalle.edu/150/content/day_grab.php',
type: "GET",
data: data,
cache: false,
success: function(html) {
$('#this-day-info').html(html);
console.log (html);
$(".left").click(function() {
$('#datepicker').datepicker( "setDate" , -1d );
});
$(".right").click(function() {
$('#datepicker').datepicker( "setDate" , +1d );
});
}
});
}
});
});
You should replace
$('#datepicker').datepicker( "setDate" , -1d );
with
$('#datepicker').datepicker( "setDate" , "-1d" );
(and the same for +1d)
A link to some examples for confirmation

Categories