Reputation: 23
I'm using jQuery to fill in a timetable information, the information is supplied in a JSON format. This is the loop that I'm using:
for (var i = 0; i < r.events.length; i++) {
myvar = r.events[i].slot;
$("#" + myvar).text( r.desc + r.events[i].type + r.events[i].rooms +
r.events[i].id + r.events[i].duration );
So I need to insert an if
statement into the loop that if the duration of the event equals 2 then the loop fills the cell AND cell +1. (The cells are named: wed09
, wed10
, wed11
, wed12
, wed13
, wed14
, wed15
, wed16
, thu09
, thu10
and so on.)
How would I code this?
Many thanks
Upvotes: 2
Views: 267
Reputation: 2175
I think the best would be to have a TimeTable class like this:
var TimeTable = function(currentCell) {
var days = ["mon", "tue", "wed", "thu", "fri"];
var hours = ["09", "10", "11", "12", "13", "14", "15", "16"];
var currentDay = days.indexOf(currentCell.substring(0,3));
var currentHour = hours.indexOf(currentCell.substring(3));
// nextCell: updates the values on the TimeTable object
var nextCell = function () {
var lastDay = days.length - 1;
if (currentHour === hours.length - 1) {
currentHour = 0;
currentDay++;
} else {
currentHour++;
}
}
// getNextCell: gets the current Cell and increments the next cell
getNextCell = function () {
var currentCell = days[currentDay] + hours[currentHour];
nextCell();
return currentCell;
}
// fill: fills (duration) times the adjacent cells
// input duration: the duration of the event ( > 0 )
// input text: the text that needs to be filled into each cell
this.fill = function (duration, text) {
for (var i = 0; i < duration; i++) {
$("#" + getNextCell()).text(text);
}
}
}
Since you talked about the duration which could be 2 or higher, I used a for loop instead of an if in the fill
method, so it would fill 3 cells if duration = 3, etc.
Finally, you need to replace your for
loop like this:
for (var i = 0; i < r.events.length; i++) {
var timeTable = new TimeTable(r.events[i].slot);
text = r.desc + '\n' + r.events[i].type + '\n' + r.events[i].rooms + '\n' + r.events[i].id + r.events[i].duration;
timeTable.fill(r.events[i].duration, text);
}
The code is in this fiddle
Upvotes: 1