Sorry for the length of this question, but there is some background you need to know to fully understand:
I am building an event scheduler in Drupal 7 which allows users to check a checkbox to add an event to their schedule... and it's a mess. The checkboxes contain a value looking similar to 1404915600 - 1404917400
which represents 10:30am - 10:50am
which is the result of using PHPs strtotime();
function like so strtotime("10:30am");
I need to check on the fly if the user checks another box with an overlapping time as a previously selected event and trigger an error if there is an overlap.
Currently, I am using the php function mentioned above to create the values in the checkboxes, and then passing those values to a javascript array on click of checkbox. The id
of the checkbox is the url friendly name of the selected event, which acts as the array key, and the values are the selected times, so the array ends up looking like:
timeArr = { event-name-one: 0: 1404915600, 1: 1404917400 }
Each event has it's own key to simplify deleting (or unscheduling) events using Javascripts delete
function.
Here is the complete code which grabs the checkbox ID and the times associated and stores them in the array:
var timeBox = jQuery('input[type="checkbox"].time, input[type="checkbox"].time2');
var timeArr = [];
// Listen for checkbox change
timeBox.bind('click', function() {
var eventID = jQuery(this).attr('id');
// If Checkbox IS checked
if(jQuery(this).prop('checked')) {
var timeStamp = jQuery(this).val();
var newTime = timeStamp.split(" - ");
// If timeArr has been set
if(timeArr.length > 1) {
for(key in timeArr) {
if(newTime[0] > timeArr[key][0] && newTime[0] < timeArr[key][1] || timeArr[key][0] > newTime[0] && timeArr[key][0] < newTime[1]) {
alert("Overlap!");
return false;
} else {
timeArr[eventID].push(newTime);
console.log(timeArr);
}
}
} else {
// else timeArr hasn't been set -- so set it!
timeArr[eventID] = newTime;
console.log(timeArr);
}
} else {
delete timeArr[eventID];
}
});
I can't seem to get the newly selected event time to cross check with the current times in the array. They just get appended to the timeArr
array as if the checks passed.
Am I going about this the complete wrong way or am I just missing something little? I've tried so many different things I'm quite lost as to which is the right direction to take. I am using Drupal 7 if that helps any.