使用多个过滤器过滤事件(复选框)

时间:2015-07-15 10:04:05

标签: fullcalendar filtering

我正在使用jQuery的完整日历和我的sharepoint日历列表。我想用多个复选框选择来过滤事件。我想根据复选框中选择的房间过滤事件。

为此,我使用以下脚本。

脚本:

<link rel="stylesheet" type="text/css" href="http://bisp2013-04:1000/sites/Exercise2/Style%20Library/FullCalendar/fullcalendar.css" />
<link rel="stylesheet" type="text/css" href="http://bisp2013-04:1000/sites/Exercise2/Style%20Library/FullCalendar/jquery-ui-1.8.16.custom.css" />

<script type="text/javascript" src="http://bisp2013-04:1000/sites/Exercise2/Style%20Library/FullCalendar/jquery-2.1.4.js"></script>
<script type="text/javascript" src="http://bisp2013-04:1000/sites/Exercise2/Style%20Library/FullCalendar/jquery-ui-1.8.16.custom.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.SPServices/0.7.1a/jquery.SPServices-0.7.1a.min.js"></script>
<script type="text/javascript" src="http://bisp2013-04:1000/sites/Exercise2/Style%20Library/FullCalendar/moment.min.js"></script>
<script type="text/javascript" src="http://bisp2013-04:1000/sites/Exercise2/Style%20Library/FullCalendar/fullcalendar.js"></script>

<script type=text/javascript">
</script>

<script type="text/javascript">
// Format UTC dates as local date/time strings.
var rooms = [];
var selectedRooms = [];
var events = [];
var filteredSource = [];
var RoomSelection = [];
var date = new Date();


function closeDialog(result) {
    SP.UI.ModalDialog.RefreshPage(result);
}
function formatDateToLocal( date ) {

    var dateUTC;

    if ( typeof date === "string" ) {

        // Convert UTC string to date object
        var d = new Date();
        var year = date.split('-')[0];
        var month = date.split('-')[1] - 1;
        var day;
        var hour;
        var minute;
        var second;
        day = date.split('-')[2].split('T')[0];
        hour = date.split('T')[1].split(':')[0];
        minute = date.split('T')[1].split(':')[1].split(':')[0];
        second = date.split('T')[1].split(':')[2].split('Z')[0];
        dateUTC = new Date( Date.UTC( year, month, day, hour, minute, second ) );
    }
    else if ( typeof date === "object" ) {
        dateUTC = date;
    }
    else {
        alert( "Date is not a valid string or date object." );
    }

    // Create local date strings from UTC date object
    var year = "" + dateUTC.getFullYear();
    var month = "" + ( dateUTC.getMonth() + 1 ); // Add 1 to month because months are zero-indexed.
    var day = "" + dateUTC.getDate();
    var hour = "" + dateUTC.getHours();
    var minute = "" + dateUTC.getMinutes();
    var second = "" + dateUTC.getSeconds();

    // Add leading zeros to single-digit months, days, hours, minutes, and seconds
    if ( month.length < 2 ) {
        month = "0" + month;
    }
    if ( day.length < 2 ) {
        day = "0" + day;
    }
    if ( hour.length < 2 ) {
        hour = "0" + hour;
    }
    if ( minute.length < 2 ) {
        minute = "0" + minute;
    }
    if ( second.length < 2 ) {
        second = "0" + second;
    }

    var localDateString = year + "-" + month + "-" + day + "T" + hour + ":" + minute + ":" + second;

    return localDateString;
}

$(document).ready( function() {

 $().SPServices({
    operation: "GetListItems",
    async: false,
    listName: "Training Rooms",
    completefunc: function (xData, Status) {
    if(Status == 'success' )
    {
        $(xData.responseXML).SPFilterNode("z:row").each(function()
        {
            var value= $(this).attr("ows_ID");
            var text = $(this).attr("ows_Title");
            var roomColor = $(this).attr("ows_bifctpEventColor")
            rooms.push({
                            title: text,
                            id: value,
                            Color: roomColor
                        });
             $("#filterBox").append ( "<input id='chk_" + value + "' type='checkbox' value='" + value + "' style='background:"+roomColor+"' onchange='FilterCalendar(" + value + ",this)'/><label for='chk_" + value + "'>" + text + "</label>" );           

        });
    }
  }
});

    $( '#calendar' ).fullCalendar({

        // Assign buttons to the header of the calendar. See FullCalendar documentation for details.
        header: {
            left:'prev,next today',
            center: 'title',
            right: 'month, agendaWeek, agendaDay'
        },

        dayClick: function (date, jsEvent, view) {

        var now = new Date();

        if (date.setHours(0,0,0,0) < now.setHours(0,0,0,0))
        {
            alert('You Can Not add Event on this date');
        }

        else
        {
            var siteUrl = window.location.protocol + "//" + window.location.host + _spPageContextInfo.siteServerRelativeUrl;
            var myLinksUrl = siteUrl + "/Lists/RoomReservation/NewForm.aspx";
            var options = {
                url: myLinksUrl,
                title: "Room Reservation",
                dialogReturnValueCallback: closeDialog
            };
            SP.SOD.execute('sp.ui.dialog.js', 'SP.UI.ModalDialog.showModalDialog', options);
        }
       },
        defaultView: "month", // Set the default view to month
        /*
                    when user select timeslot this option code will execute.
                    It has three arguments. Start,end and allDay.
                    Start means starting time of event.
                    End means ending time of event.
                    allDay means if events is for entire day or not.
                */
        selectable: true,
        selectHelper: true,
        select: function(start, end, allDay)
        {
             if(start < date)
            {
                // Do whatever you want here.
                alert('Cannot select this dates.');
                return;
            }
            var title = prompt('Event Title:');
            if (title) {
                $( '#calendar' ).fullCalendar('renderEvent', {
                    title: title,
                    start: start,
                    end: end,
                    allDay: allDay
                },
                true // make the event "stick"
                );
            }

            $( '#calendar' ).fullCalendar('unselect');
        },
        editable: true,

        // Add events to the calendar. 
        events: function( start, end, callback ) {

            // Create an array to hold the events.
        events = [];

            // Set the date from which to pull events based on the first visible day in the current calendar view. For a month view, this will usually be several days into the previous month. We can use FullCalendar's built-in getView method along with the formatDate utility function to create a date string in the format that SharePoint requires. It must be in the format YYYY-MM-DDTHH:MM:SSZ. Due to time zone differences, we will omit everything after the day.
        var startDate = moment().format($('#calendar').fullCalendar('getView').intervalstart, "u").split("T")[0];

            // Get the current view of the calendar (agendaWeek, agendaDay, month, etc.). Then set the camlView to the appropriate value to pass to the web service. This way we will only retrieve events needed by the current view (e.g. the agendaWeek view will only retrieve events during the current week rather than getting all events for the current month).
            var calView = $( '#calendar' ).fullCalendar( 'getView' ).title;
            var camlView = "";

            switch( calView ) {
                case "agendaWeek":
                    camlView = "<Week />";
                    break;
                case "agendaDay":
                    camlView = "<Week />";
                    break;
                default: // Default to month view
                    camlView = "<Month />";
            }

            // Set the camlFields, camlQuery, and camlOptions to the appropriate values to pass to the web service. You can add additional <ViewFields /> or adjust the CAML query if you have some custom columns that you want to filter by or display data from. The values below are the pretty much the minimum you'll want to start from to get it working.
            var camlFields = "<ViewFields><FieldRef Name='Title' /><FieldRef Name='EventDate' /><FieldRef Name='EndDate' /><FieldRef Name='Location' /><FieldRef Name='Description' /><FieldRef Name='fRecurrence' /><FieldRef Name='RecurrenceData' /><FieldRef Name='RecurrenceID' /><FieldRef Name='fAllDayEvent' /></ViewFields>";
            var camlQuery = "<Query><Where><And><Geq><FieldRef Name='EventDate' /><Value IncludeTimeValue='TRUE' Type='DateTime'>"+moment(start).toISOString()+"</Value></Geq><Leq><FieldRef Name='EndDate' /><Value IncludeTimeValue='TRUE' Type='DateTime'>"+moment(end).toISOString()+"</Value></Leq></And></Where></Query>";
            var camlOptions = "<QueryOptions><CalendarDate>" + startDate + "</CalendarDate><RecurrencePatternXMLVersion>v3</RecurrencePatternXMLVersion><ExpandRecurrence>TRUE</ExpandRecurrence><DateInUtc>TRUE</DateInUtc></QueryOptions>";

            // Make the web service call to retrieve events.
            $().SPServices({
                operation: "GetListItems",
                async: false,
                listName: "Room Reservation", // Change this to the GUID or display name of your calendar. If the calendar is on a different site, you can use the display name with the webURL option (see SPServices.CodePlex.com for more information).
                CAMLViewFields: camlFields,
                CAMLQuery: camlQuery,
                CAMLQueryOptions: camlOptions,
                completefunc: function( xData, Status ) {
                    $( xData.responseXML ).find( "z\\:row, row" ).each( function() {

                        // Check for all day events
                        var fADE = $( this ).attr( 'ows_fAllDayEvent' );
                        var thisADE = false;
                        var thisStart;
                        var thisEnd;

                        if ( typeof fADE !== "undefined" && fADE !== "0" ) {
                            thisADE = true;
                            // Get the start and end date/time of the event. FullCalendar will parse date strings in local time automagically, and we don't need to do any local time conversions for all day events, so we can use the UTC date strings from SharePoint without converting them to local time.
                            var thisStart = $( this ).attr( 'ows_EventDate' );
                            var thisEnd = $( this ).attr( 'ows_EndDate' );
                        }
                        else {
                            // Get the start and end date/time of the event. FullCalendar will parse date strings in local time automagically, so we need to convert the UTC date strings from SharePoint into local time. The formatDateToLocal() function above will take care of this. See comments in that function for more information.
                            var thisStart = formatDateToLocal( $( this ).attr( 'ows_EventDate' ) );
                            var thisEnd = formatDateToLocal( $( this ).attr( 'ows_EndDate' ) );
                        }

                        // Get the list item ID and recurrence date if present. This will be used to generate the ID query string parameter to link to the event (or the specific instance of a recurring event). The ID query string parameter must be in the format "ID.0.yyyy-MM-ddTHH:mm:ssZ" for recurring events (where "ID" is the list item ID for the event). Event ID's are returned as just a number (for non-recurring events) or several numbers separated by ";#" in 2007 or "." in 2010 to indicate individual instances of recurring events. By splitting and joining the ID this way, thisID will be set to a valid query string parameter whether an event is recurring or not for both versions of SharePoint.
                        var thisID = $( this ).attr( 'ows_ID' ).split( ';#' ).join( '.' );
                        var thisRoom = $(this).attr('ows_bifctpTrainingRoom').split(';#')[0];
                        // FullCalendar documentation specifies that recurring events should all have the same id value when building the events array (the id is optional, but I'm including it for completeness). We can get the list item ID (which is the same for all instances of recurring events) without the recurrence information by simply splitting thisID.
                        var eventID = thisID.split( '.' )[0];

                        // Get the event title. This is displayed on the calendar along with the start time of the event.
                        var thisTitle = $( this ).attr( 'ows_Title' );

                        // Get the event description. I don't use it in this example, but you could use it for something, perhaps as a tooltip when hovering over the event.
                        var thisDesc = $( this ).attr( 'ows_Description' );

                        // Add the event information to the events array so FullCalendar can display it.
                        events.push({
                            title: thisTitle,
                            id: eventID,
                            start: thisStart,
                            end: thisEnd,
                            allDay: thisADE,
                            room:thisRoom,                          
                            // Adjust this URL to link to the display form for your calendar events. You can include a Source parameter to allow users to easily return to the FullCalendar page.
                            url: _spPageContextInfo.siteAbsoluteUrl + '/Lists/RoomReservation/DispForm.aspx?ID=' + thisID + '&Source=' + window.location,
                            description: 'Check Calendar Events'
                        });

                    });

                    callback( events );

                }


            });

        },

        eventRender: function eventRender( event, element, view ) {
        var isFound = false;
        var backgroundColor = "";
        for (var roomID in rooms) {
        var currentRoom = rooms[roomID];
        if (currentRoom.id == event.room) {

            backgroundColor = currentRoom.Color;
            element.find(".fc-event-time").html(event.start.format("HH:mm") + "-" + event.end.format("HH:mm"));
            element.find(".fc-title").parent().attr("title", event.title);
            element.css('color','black');
            element.find('.fc-event-skin').css('background-color', backgroundColor); 
            element.css('background-color', backgroundColor);
            isFound = true;
            break;
        }
        }
        return isFound;    
}

    });
})
</script>
<style type="text/css">

        #calendar
        {
            width: 900px;
            margin: 0 auto;
        }
    </style>

<div id="filterBox">

</div>
<div id="calendar">

    <!-- Calendar will be added here -->

</div><!-- #calendar -->

这就是我的屏幕目前的样子: enter image description here

我想要做的是每个复选框的更改事件。我想过滤日历事件并仅显示所选房间的事件。

0 个答案:

没有答案