I am trying to create a page that grabs a set of PDFs sorted by date. I can't seem to increment the date correctly. I'm not sure what's going wrong here. I rewrote the code twice now. No luck.
The current issue is that the set variables for the date do not keep the value of the date as a whole. IE incrementing from 12, 31, 2018, or in the case of the URL format 20181231, should result urlIncremented=20190101. January 1st, 2019, but the result of my code is urlIncremented=20181232.
The end result of one loop if set to June 8th 2018, should be: url20180608
I've searched for advice on here, and found a JS file called Date.JS; I've imported it and it was looking promising but just consoles out a part of its code, namely:
function () {
if (this._isSecond) {
this._isSecond=false;
return this;
}
if (this._same) {
this._same=this._is=false;
var o1=this.toObject(),
o2=(arguments[0] || new Date()).toObject(),
v="",
k=j.toLowerCase();
for (var m=(px.length-1); m>-1; m--) {
v=px[m].toLowerCase();
if (o1[v]!=o2[v]) {
return false;
}
if (k==v) {
break;
}
}
return true;
}
if (j.substring(j.length-1)!="s") {
j+="s";
}
return this["add"+j](this._orient);
}
Just a heads up I do not yet know jQuery, I was just playing with it to see if it would help..
Here is my actual code.
let url = "blank",
firstRun = true;
/*
function setDateByIncrement(currentSetDate){
let newDate,
currentDate = new Date(),
day = currentDate.getDate()+1,
month = currentDate.getMonth() + 1,
year = currentDate.getFullYear();
console.log(newDate);
newDate = (year+month+day);
console.log(newDate);
return newDate;
}
*/
// use on First run to set the url and date.
//3
function setURL(){
let urlIncremented = url + dateIncrementMethod();
return urlIncremented;
}
// will open x number of new windows containing URL
//2
function grabOpenPDF(maxNumberDays){
let urlSet = setURL();
//Set the variable for max days.
for(let x = 0; x < maxNumberDays; x++){
//window.open(urlSet);
console.log("It works: " + x);
urlSet = setURL();
}
}
/* TODO Add automatic download for MASS print.
function downloadPDF(){
}
*/
//Starts the task.
//1
function start(load){
console.log("Current Address: " + url);
if(load === 1){
console.log("Event load active. ");
let maxDay = document.querySelector('#maxNumberDays').value;;
grabOpenPDF(maxDay);
}else{
console.log("Event load skip. ")
let maxDay = document.getElementById('maxNumberDays').value;
}
}
//4
function dateIncrementMethod(current){
let dateIncrement;
if(firstRun=== true){
var today = new Date($('#date-input').val());
console.log("FirstRun check in 4. ")
}
firstRun = false;
var tomorrow = today.add(1).day;
console.log(tomorrow);
return tomorrow;
}
/* Possibly Deprecated
//let dateIncrement;
let date = new Date($('#date-input').val());
console.log(date);
day = date.getDate() + 1;
if(firstRun === true){
month = date.getMonth() + 1;
year = date.getFullYear();
//dateIncrement = (parseToAPI(year, month, day));
firstRun = false;
parseToAPI(year, month, day);
}else{
day = date.getDate()+1;
parseToAPI(year, month, day);
}
}
*/
function parseToAPI(year, month, day){
let apiDate;
console.log("Entered parse");
this.day = day;
this.month = month;
let d = this.day.toString(),
m = this.month.toString();
if(d.length === 1){
console.log("Entered First IF");
this.day = ('0') + day;
//console.log(day);
}
if(m.length === 1){
console.log("Entered Second IF")
this.month = ('0') + month;
}
apiDate = (year + "" + "" + month + "" + day);
console.log(apiDate);
return apiDate;
}
<!DOCTYPE html>
<html>
<script src="https://code.jquery.com/jquery-2.0.3.js"></script>
<script src="https://doc-0k-6g-docs.googleusercontent.com/docs/securesc/77gdpvi38k94jj7nmfcm2n3tq7a0ifhu/ehjuusajghqnne5r2ncfvj30cmbll20p/1545105600000/17500114768188980350/17500114768188980350/1CDff-uWGahZX7aLt6WQfV1-R5PFHwiK8?e=download&nonce=52qkphatg2scm&user=17500114768188980350&hash=3uc9iql9m90vcrv3a7mhg8fdjce1b4fe.js"></script>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input type="date" id="date-input" required />
<input type="maxNumberDays" id="maxNumberDays" max="31" required />
<button id="startPDFApp" onClick="start()">Print PDFs</button>
<button id="startPDFApp" onClick="start(1)">Load PDFs</button>
<div id="info"></div>
</body>
</html>
While I haven't invested enough time trying to understand what you're really trying to do, it seems like there's a lot of unnecessary code. I'll leave it to you to decipher what you need.
I can only express that the below code is in an in-between state. It includes a number of changes, most of which I'll point out, but I didn't want to change it too drastically that it all looked foreign. So even the code below has much to be improved on.
Significant changes include:
Because your URL is increasing by one, you may benefit by using a function generator. Inside it increases the date by calling setDate on itself using it's own date + 1. It also uses a string function, padStart, to ensure months and days are always two-digit.
Getting rid of firstRun variable as it is no longer needed
Inside your grabOpenPDF, all you need to do is get the next value returned by the URL generator function
let URL_GEN = UrlGenerator('blank'),
URL = URL_GEN.next().value;
//Starts the task.
//1
function start(load) {
let startDate = new Date(document.querySelector('#date-input').value)
// overwrite global with values
URL_GEN = UrlGenerator('blank', startDate)
URL = URL_GEN.next().value
console.log("Current Address: " + URL);
if (load === 1) {
console.log("Event load active.");
let maxDay = document.querySelector('#maxNumberDays').value;
grabOpenPDF(maxDay);
} else {
console.log("Event load skip.")
let maxDay = document.getElementById('maxNumberDays').value;
}
}
/* URL generator */
function* UrlGenerator(url, dt=new Date()) {
while (true){
yield url + dt.getFullYear() + (''+(dt.getMonth()+1)).padStart(2,'0') + (''+dt.getDate()).padStart(2,'0');
// increase day for next iteration
dt.setDate(dt.getDate()+1);
}
}
// will open x number of new windows containing URL
function grabOpenPDF(maxNumberDays) {
//Set the variable for max days.
for (let i=0; i < maxNumberDays; i++) {
console.log("It works: " + i, URL);
URL = URL_GEN.next().value;
}
}
<script src="https://doc-0k-6g-docs.googleusercontent.com/docs/securesc/77gdpvi38k94jj7nmfcm2n3tq7a0ifhu/ehjuusajghqnne5r2ncfvj30cmbll20p/1545105600000/17500114768188980350/17500114768188980350/1CDff-uWGahZX7aLt6WQfV1-R5PFHwiK8?e=download&nonce=52qkphatg2scm&user=17500114768188980350&hash=3uc9iql9m90vcrv3a7mhg8fdjce1b4fe.js"></script>
<input type="date" id="date-input" value="12/29/2018" required />
<input type="maxNumberDays" id="maxNumberDays" value="5" max="31" required />
<button id="startPDFApp" onClick="start()">Print PDFs</button>
<button id="startPDFApp" onClick="start(1)">Load PDFs</button>
<div id="info"></div>
This can be further improved by better management of your globals, more straightforward code (more simply laid out), and perhaps better naming conventions. Also, it's generally a no-no to be putting event handlers directly in the HTML these days, you could bind those event dynamically via JavaScript.
I can't seem to increment the date correctly.
If you have a dates like "20181231" with a format YYYYMMDD, you must parse it to the date parts, increment the day, then format it back to an appropriate string. A date manipulation library can help, or you can write a custom function.
You can do it without generating a Date, but it's a bit more code and logic.
E.g.
// Accept date string in format YYYYMMDD
// and return next date in same format
function getNextDate(s) {
let z = n => ('0'+n).slice(-2);
let [y, m, d] = s.match(/^\d{4}|\d{2}/g);
let date = new Date(y, m-1, d);
date.setDate(date.getDate() + 1);
return date.getFullYear() + z(date.getMonth()+1) + z(date.getDate());
}
['20181230','20181231','20190101'].forEach(
s => console.log(`${s} => ${getNextDate(s)}`)
);
You can also use a library like moment.js:
function getNextDate(s) {
return moment(s, 'YYYYMMDD')
.add(1, 'day')
.format('YYYYMMDD');
}
['20181230','20181231','20190101'].forEach(
s => console.log(`${s} => ${getNextDate(s)}`)
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
If you are using moment.js for other things, include it. But if this is the only date stuff you need it for, it's a bit of overhead you don't need.
A lot of your code is a little unclear and the logic is not obvious, in regards to what should happen. Here is what I could gleam:
User should enter a Date, that is required
When user click Load PDF, a list of dates should be calculated
Assuming today until selected date, with a max of 31 days in the future
The script checks if a PDF exists for each of the days in the list
I suspect you were just looking for a way to generate a pattern for the days. I may have more here than you need.
$(function() {
function grabOpenPDF(end) {
var current = new Date();
end.setDate(end.getDate() + 1);
var urls = [];
while (current < end) {
urls.push({
name: $.datepicker.formatDate("yymmdd", current),
url: "https://example.com/getpdf.php?date=" + $.datepicker.formatDate("yymmdd", current),
hit: null
});
current.setDate(current.getDate() + 1);
};
console.log(urls);
$.each(urls, function(k, v) {
$.ajax({
url: v.url,
success: function(data) {
v.hit = true;
$("#info").append("<div>" + (k + 1) + ". " + v.url + ", hit: " + v.hit.toString() + "</div>");
},
error: function(data) {
v.hit = false;
$("#info").append("<div>" + (k + 1) + ". " + v.url + ", hit: " + v.hit.toString() + "</div>");
}
});
});
}
var dtInp = $("#date-input").datepicker({
dateFormat: "mm/dd/yy",
maxDate: "+31d",
minDate: new Date()
});
$(".today").html($.datepicker.formatDate("mm/dd/yy", new Date()));
$("#printPDF").click();
$("#startPDF").click(function(e) {
e.preventDefault();
$("#info").html("");
if ($("#date-input").val() === "") {
$("#date-input").focus();
return false;
}
console.log("Event load active.");
grabOpenPDF(dtInp.datepicker("getDate"));
});
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://doc-0k-6g-docs.googleusercontent.com/docs/securesc/77gdpvi38k94jj7nmfcm2n3tq7a0ifhu/ehjuusajghqnne5r2ncfvj30cmbll20p/1545105600000/17500114768188980350/17500114768188980350/1CDff-uWGahZX7aLt6WQfV1-R5PFHwiK8?e=download&nonce=52qkphatg2scm&user=17500114768188980350&hash=3uc9iql9m90vcrv3a7mhg8fdjce1b4fe.js"></script>
<div class="ui-widget ui-widget-content" style="padding: 7px;">
<p>From <span class="today">Today</span> until <input type="text" id="date-input" placeholder="mm/dd/yy" required style="border: 0; width: 8em; border-radius: 0; border-bottom: 1px solid #eee;" /></p>
<button id="printPDF">Print PDFs</button>
<button id="startPDF">Load PDFs</button>
<div id="info"></div>
</div>
As I mentioned, you can use jQuery and jQuery UI to help you out. Take a look: http://api.jqueryui.com/datepicker/
When the user clicks on the field, they can select a date between today and 31 days into the future. they can then click the "Load PDF" button and it will grab the PDFs by iterating each day and performing some action.
Good reference for incrementing the date: Incrementing a date in JavaScript
Personally, I would push this off to the server instead of doing this in the browser. Assuming there is a DB of PDFs, it would be faster to send a start and end date to the server and have it perform a SELECT query and return the results. You're sending two bits of data to the server and getting a list of results versus hammering around for PDFs hoping to find your nail. using the above example, you could set the option, minDate: "-6m" and just limit the range the user might select a start and end date.
Hope this helps. Feel free to comment and ask for more clarity if needed.
Related
I have a range DatePicker from Primefaces.
But I also want to be able to just select one date.
But if i do so, i won't get any values, just a empty array.
This is because the internal function (which i can't modify) only returns something when two values are given. Or at least I think that.
The workaround which i thought of was just taking the first value of the array by calling it with a javascript function, but i can't access it, because the PF function has neither a function name nor a class.
Here the code of the PrimeFaces function:
if (this.isRangeSelection()) {
if (this.value && this.value.length) {
var b = this.value[0],
g = this.value[1];
d = this.formatDateTime(b);
if (g) {
d += " " + this.options.rangeSeparator + " " + this.formatDateTime(g)
}
}
}
Here is my poor javascript attempt:
<script type="text/javascript">
function getArrayValue(){
console.log("inFunction");
console.log(window.d.value[0]);
}
</script>
This is called with this:
<div class="p-field p-col-12 p-md-4">
<p:datePicker id="range" selectionMode="range"
value="#{SearchBean.range}" onblur="getArrayValue()">
</p:datePicker>
</div>
Thanks for your help in advance! :)
I just helped a friend do the same thing that sets the range to both dates being the same you can do it with this JS...
<script type="text/javascript">
function adjustDateRange(widgetVar) {
var widget = PF(widgetVar);
var dates = widget.getDate();
if (dates[0] && !dates[1]) {
dates[1] = dates[0];
widget.jq.data().primeDatePicker.updateModel(null, dates);
}
}
</script>
Then in your DatePicker...
<p:datePicker id="range"
widgetVar="wgtRange"
selectionMode="range"
value="#{SearchBean.range}"
onblur="adjustDateRange('wgtRange')">
</p:datePicker>
How can i check when a value on input is changed.
I have a calendar and when i click on calendar it changes the value on input , but when im trying to see if it has changed its not working. i have tried AddEventListener, also jquery on change, also i sent a function on change to call it but none of them is working.
<input type="text" id="date" class="date" onchange="changed()" name="" >
function changed(){
alert("hello world");
}
Main js file for creating the calendar :
This function creates the calendar on my php file .
And then when on click it gets the value on the input with id #date
But When im trying to see if value has changed it is not working .
// Initialize the calendar by appending the HTML dates
function init_calendar(date) {
$(".tbody").empty();
$(".events-container").empty();
var calendar_days = $(".tbody");
var month = date.getMonth();
var year = date.getFullYear();
var day_count = days_in_month(month, year);
var row = $("<tr class='table-row'></tr>");
var today = date.getDate();
// Set date to 1 to find the first day of the month
date.setDate(1);
var first_day = date.getDay();
// 35+firstDay is the number of date elements to be added to the dates table
// 35 is from (7 days in a week) * (up to 5 rows of dates in a month)
for(var i=0; i<35+first_day; i++) {
// Since some of the elements will be blank,
// need to calculate actual date from index
var day = i-first_day+1;
// If it is a sunday, make a new row
if(i%7===0) {
calendar_days.append(row);
row = $("<tr class='table-row'></tr>");
}
// if current index isn't a day in this month, make it blank
if(i < first_day || day > day_count) {
var curr_date = $("<td class='table-date nil'>"+"</td>");
row.append(curr_date);
}
else {
var monthplusone = months[month];
var curr_date = $("<td class='table-date' id='"+day+"-"+monthplusone+"-"+year+"'>"+day+"</td>");
var events = check_events(day, month+1, year);
if(today===day && $(".active-date").length===0) {
curr_date.addClass("active-date");
let x = document.getElementById('date').value=day+"-"+monthplusone+"-"+year;
$('.table-date').ready(function () {
x.value;
});
show_events(events, months[month], day);
}
// If this date has any events, style it with .event-date
if(events.length!==0) {
curr_date.addClass("event-date");
}
// Set onClick handler for clicking a date
$('.table-date').on('click', function () {
document.getElementById('date').value = $(this).attr('id');
});
curr_date.click({events: events, month: months[month], day:day}, date_click);
row.append(curr_date);
}
}
// Append the last row and set the current year
calendar_days.append(row);
$(".year").text(year);
}
Notice that change is actually triggered when the input is not focused anymore.
document.getElementById("date").addEventListener("change", function () {
alert("hello world");
});
<input type="text" id="date" class="date" name="">
This works. Not sure where you're running into an issue.
function changed(){
console.log("hello world");
}
<input type="text" id="date" class="date" onchange="changed()" name="" >
EDIT: Shortened version of init_calender() for others interested in answering:
function setDate() {
document.getElementById("date").value = '19-Dec-2021'
}
I basically agree with #Spankied in that you should try and shorten your code to the point where you are having the issue. However, after looking at your code it seems to me that you want the following function
$('.table-date').on('click', function () {
document.getElementById('date').value = $(this).attr('id');
});
to not only change the value in your #date input but also trigger its change event-handler function. You can do that by changing it to something like
$('.table-date').on('click', function () {
document.getElementById('date').value = $(this).attr('id');
$("#date" ).change();
});
jQuery.change() without any arguments will trigger a predefined "change"-event on the DOM-object that is selected by the jQuery-object.
You can use js to do that:
let x = $(...) //select the input box
let val = x.value;
function repeat() {
if (val !== x.value) {
change()
}
}
setInterval(repeat, 100)
This checks if the result is the same.
This might make your site a bit slow and it might look odd but this will work in just every case
<script>
let Oldvalue = $('.date')[0].val();
setInterval(() => {
let currentValue = $('.data')[0].val()
if (Oldvalue != currentValue){
//do whatever but in end write this
Oldvalue = currentValue;
}
}, 10);
</script>
I have a small web calculator which calculates time. My mobile browser gets rid of all data when I've minimised/closed the mobile broswer for a few minutes or on a page refresh so I've made a button which can reload all previous data and displays as text.
I want to get rid of the "Get old data" button and just have the page reload with all the values displayed in the input box as they were before the page refresh.
I've been thinking an onload event in the input box would work but as i understand this is not possible.
HTML
<body onload="getreload()">
<p>Please enter minutes</p>
<input type="text" id="etime">
<br>
<p>Please enter time in 24 hour format (eg. 15:00)</p>
<input type="text" id="stime">
<br>
<br>
<button onclick="myFunction()">Calculate</button>
<p id="finishtime">
<br>
<br>
<button onclick="getreload()">Get old data</button>
<p id="finishtime2">
<p id="mintime2">
</body>
Javascript
function myFunction() {
function converToMinutes(s) {
var c = s.split(':');
return parseInt(c[0]) * 60 + parseInt(c[1]);
}
function parseTime(s) {
var seconds = parseInt(s) % 60;
return Math.floor(parseInt(s) / 60) + ":" + ((seconds < 10)?"0"+seconds:seconds);
}
var endTime = document.getElementById("etime").value;
var startTime = converToMinutes(document.getElementById("stime").value);
var converted = parseTime(startTime - endTime);
document.getElementById('finishtime').innerHTML = "You will finish your break at " + converted;
if (typeof(Storage) !== "undefined") {
localStorage.setItem("convertedTime", converted);
localStorage.setItem("endTimeReload", endTime);
} else {
// Sorry! No Web Storage support
}
}
function getreload() {
var convertedTime = localStorage.getItem("convertedTime");
document.getElementById('finishtime2').innerHTML = "End of break time: " + convertedTime;
var endTimeReload = localStorage.getItem("endTimeReload");
document.getElementById('mintime2').innerHTML = "Minutes till next client: " + endTimeReload;
}
You are mostly there, but you are not restoring correctly and not saving the startTime.
Here is a fiddle with everything you need:
https://jsfiddle.net/22ej8scw/
Restore like this. (I also changed how it is saved)
function getreload() {
var startTime = localStorage.getItem("startTime");
document.getElementById("stime").value = startTime;
var endTimeReload = localStorage.getItem("endTimeReload");
document.getElementById("etime").value = endTimeReload;
if (startTime && endTimeReload)
myFunction();
}
So after you've calculated a time, you want those values to be there if you refresh the page?
When you calculate, save all the values in localstorage, then when the page loads (body element's 'onload') set the input boxes values to the corresponding localstorage ones (checking to make sure those values exist first)
I am programming a dynamic javascript calendar on which events can be added by two persons, the manager and the associate. But, only the text box with the mentioned date appears on the browser.
Is there a mistake in the logic?
Please help!
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.calendarMonth{
border-collapse:collapse;
background-color:#eef;
}
.calendarMonth th{
}
.calendarMonth .calendarTitle{
background-color:#ddf;
}
.calendarMonth .calendarPrevious{
background-color:#ddf;
}
.calendarMonth .calendarNext{
background-color:#ddf;
}
.calendarEmpty{
}
.calendarDay{
background:#fff;
border:1px solid black;
text-align:center;
width:2em;
}
</style>
<script type="text/javascript">
var daysInMonth=[31,28,31,30,31,30,31,31,30,31,30,31];
var monthNames=['January','February','March','April','May','June','July','August','September','October','November','December'];
// Returns the number of days in the month in a given year (January=0)
function getDaysInMonth(month,year){
if ((month==1)&&(year%4==0)&&((year%100!=0)||(year%400==0))){
return 29;
}else{
return daysInMonth[month];
}
}
// Performs an action when a date is clicked
function dateClicked(day,month,year){
document.forms.calendar.date.value = day+'/'+month+'/'+year;
}
// Sets the displayed month
function setDisplayedMonth(month){
if (month<0){
alert('You have reached the beginning of this calendar');
}else if (month>=months){
alert('You have reached the end of this calendar');
}else{
for (var i=0;i<months;i++){
document.getElementById('calendarMonth'+i).style.display='none';
}
document.getElementById('calendarMonth'+month).style.display='block';
}
}
</script>
</head>
<body>
<form id="calendar">
<table>
<tr>
<td><label for="date">Date:</label></td>
<td><input type="text" id="date" name="date" value="28/05/2015"></td>
</tr>
<tr><td></td><td>
<script type="text/javascript">
var month=0;
var year=2015;
var months=12;
for (var i=0;i<months;i++){
document.writeln('<table class="calendarMonth" '+'id="calendarMonth'+i+'" cellspacing="0">');
document.writeln('<tr>'
+'<th class="calendarPrevious" onClick="setDisplayedMonth('+(i-1)+')"><</th>'+'<th class="calendarTitle" colspan="5">' +monthNames[month]+' '+year+'</th>'+'<th class="calendarNext" onClick="setDisplayedMonth('+(i+1)+')">></th>'+'</tr>');
document.writeln('<tr><th>Sun</th><th>Mon</th><th>Tue</th>'+'<th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th></tr>');
var firstDayDate=new Date(year,month,1);
var firstDay=firstDayDate.getDay();
for (j=0;j<42;j++){
if (j%7==0) document.write('<tr>')
if ((j=firstDay+getDaysInMonth(month,year))){
document.write('<td class="calendarEmpty"></td>');
}else{
document.write('<td class="calendarDay" '+'onClick="dateClicked('+(j-firstDay+1)+','+(month+1)+','+year+')">'+(j-firstDay+1)+'');
}
if (j%7==6) document.write('</tr>');
}
document.writeln('</table>');
month++;
if (month>=12){
month=0;
year++;
}
}
setDisplayedMonth(5);
</script>
</td></tr>
</table>
</form>
</body>
</html>
Also, how can I highlight the date selected by a manager on the associate calendar?
Try using jQuery ui datepicker and use option beforeShowDay to highlight dates
$(function() {
var specialDates = {};
var now = new Date();
specialDates['10' + now.getMonth() + '' + now.getFullYear()] = [true, 'mg-special', 'By Manager'];
specialDates['25' + now.getMonth() + '' + now.getFullYear()] = [true, 'as-special', 'By Associate'];
var others = [true, '', ''];
$("#datepicker").datepicker({
'beforeShowDay': function(date) {
var target = date.getDate() + '' + date.getMonth() + '' + date.getFullYear();
return specialDates[target] || others;
},
'inline': true
});
});
td.mg-special {
background: sandybrown;
}
td.as-special {
background: brown;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<p>Date:
<input type="text" id="datepicker">
</p>
I have revised my response having not got it right first time:
try replacing your for loop with:
for (j=0; j<42; j++){
if (j%7==0) {document.write('<tr>')};
var l=firstDay;
var k=firstDay+getDaysInMonth(month,year);
if (j>=k){
document.write('<td class="calendarEmpty"></td>');
}else if (j<l){
document.write('<td class="calendarEmpty"></td>');
}else{
document.write('<td class="calendarDay" '+'onClick="dateClicked('+(j-firstDay+1)+','+(month+1)+','+year+',this)">'+(j-firstDay+1)+'');
}
if (j%7==6) document.write('</tr>');
}
regarding highlighting the cell on select by manager, you already have a cell click function so build on that e.g by using:
// Performs an action when a date is clicked
function dateClicked(day,month,year,obj){
document.forms.calendar.date.value = day+'/'+month+'/'+year;
obj.style.backgroundColor = 'yellow'
}
note the addition of "this" to the onclick event.
For any more detail i would need to know how your differentiating between inputs made by manager or associate.
if you are intending to bring the managers date in as being set somewhere else as somedate, you could try something like this in place of your for loop:
var firstDayDate=new Date(year,month,1);
var firstDay=firstDayDate.getDay();
var managersdate=new Date (somedate);
var managersday=managersdate.getDay();
var managersmonth=managersdate.getMonth();
for (j=0; j<42; j++){
if (j%7==0) {document.write('<tr>')};
var l=firstDay;
var k=firstDay+getDaysInMonth(month,year);
if (j>=k){
document.write('<td class="calendarEmpty"></td>');
}else if (j<l){
document.write('<td class="calendarEmpty"></td>');
}else{
if(j-l==managersday && i==managersmonth){
document.write('<td class="calendarDay" style="background-Color:Yellow" '+'onClick="dateClicked('+(j-firstDay+1)+','+(month+1)+','+year+',this)">'+(j-firstDay+1)+'');
}else{document.write('<td class="calendarDay" '+'onClick="dateClicked('+(j-firstDay+1)+','+(month+1)+','+year+',this)">'+(j-firstDay+1)+'');
}
}
It may also be nice to add a hover color of your choosing via css:
.calendarDay:hover {background-color: green}
Hope this helps.
I think its worthwhile responding to your comment about retrieving and parsing csv as a seperate question.
Parsing is in common language the splitting of a sentence into its component words. Most commonly we would use it to 'parse or split' data held in formats such as XML or JSON which i recomend you look at as more capable methods, but CSV is still a valid format.
Firstly retrieving your csv, if we were using jquery it would be:
$.ajax({
type: "GET",
url: "ManagersDates.csv",
dataType: "text",
success: function(data) {processData(data);}
});
there are even shorter methods available via get and post in jquery.
But presuming you wish to stick with JS for this too (no jquery) then the following is about as simple as we can get to retrieve your csv:
var request = new XMLHttpRequest(); // you may use "new ActiveXObject("MSXML2.XMLHTTP")" for ie6 and below
request.open('GET', 'ManagersDates.csv', false);
request.send();
var managersdate=(request.responsetext);
your csv now exists in the variable "managersdate" but you need to "Split or Parse" it from one long string into its component parts, there are plenty of ways to do this one method is as follows:
var mdates = new Array();
mdates = managersdate.split(",");
you now have an array holding your csv values and need to extract the correct date from it, if your date is the third item (count starts at 0) then this should return your date:
managersdate=(mdates[2]);
There are tons of excelent posts on parsing data and plenty on JSON and XML that are well worth looking up.
Good luck
I'm in the process of making a Christmas calendar, and I have an overlay which should open if the date is ex 1.12.13, otherwise it should alert the amount of days until it's available. I've tried a lot of different things but can't get it to work.
Here is what should be displayed if date is something:
<!-- overlayed element, which is styled with external stylesheet -->
<div class="apple_overlay black" id="photo1">
<img src="images/onecom.png" alt="onecom" width="496" height="496" />
<div class="details">
<h2>December 1st</h2>
<p>
Some script that does something
</p>
</div>
</div>
What I have tried
function dooropen(door) {
today=new Date();
daynow=today.getDate();
monthnow=today.getMonth();
if (monthnow!=11 && monthnow!=0) {
alert("This feature opens in December. Please come back then.");
return false;
}
if (daynow==door-1) {
alert("Come back tomorrow to see what's behind that door!");
return false;
}
if (door>daynow) {
alert("You\'ll have to wait "+(door-daynow)+" days before that door's available!");
return false;
}
}
This may work, as i can see you may have some different div for each day of the month since you are using numeric id id="photo1">, so you can try to get the dates :
var today = new Date();
var dd = today.getDate() + 1;
var mm = today.getMonth() + 1;
after that get the main parent of all divs and put it in a jquery object:
var $number_of_objects = $("#parent_div img");
once you have all those you need to put them inside a for loop to count them and match to later exit the function:
for (var i = 1; i < $number_of_objects.length; i++) {
console.log("value of i " + i);
if(i == dd){
console.log(' break');
break;
}
$("#apple img[rel='#photo"+i+"']").overlay({
effect: 'apple'
});
}
it should give you a good start point to improve it and add more feature to the script :)
happy coding
<script>
var date = new Date(),
year = date.getYear(),
month = date.getMonth()+1,
day = date.getDate();
if(day == 13){ // today is 13
code
}else{
code
}
</script>
Just show the element you want at the end of your method..
$('#photo1').show();