0

I have document library A, document library B and document library C. Every library has kinda many items in it. Now I would like to have a counter, which counts the amount of all items and makes a sum out of it. I'm searching for a JavaScript solution for this, so that I can display the amount of items for example in a Content Editor Web Part on any other Site of the same Site Collection.

  • 1
    You want to count the number of items in doc lib A, B and C and sum them and show the sum on another page somewhere? – Submits Jun 30 '16 at 11:46
  • That is exactly what I want to realise :) – SteffPoint Jun 30 '16 at 11:47
2

I answered a similar question here.

Your JavaScript would look similar to this (note the use of jQuery):

var count = 0;

$.when(
    RestGet("listname1", "yourErrorDiv", "Couldn't get from listname1"),
    RestGet("listname2", "yourErrorDiv", "Couldn't get from listname2"),
    RestGet("listname3", "yourErrorDiv", "Couldn't get from listname3")).done(function () {
        // Output results to screen, e.g.:        
        yourdiv.html(count);
    });

// @listName, the name of the list to pull data from
// @errorDiv, a string containing the ID attribute of the DIV that the error message should be displayed in. If this is ommitted, no error message will be displayed on the page
// @errorMessage, a string containing the error message that should be displayed if the call fails
function RestGet(listName, errorDiv, errorMessage) {
    var dfd = $.Deferred();
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        },
        success: function (data) {
            count = count + data.d.results.length;
            dfd.resolve();
        },
        error: function (data) {
            $(String.format("[id='{0}']", errorDiv)).html(message + " Check your browser's console for details of the error.");
            console.log(JSON.stringify(data));
            dfd.reject();
        }
    });
    return dfd;
}
  • 2
    You can save on a lot of bytes (and thus load time) when you make it odata=nometadata – Danny '365CSI' Engelman Jun 30 '16 at 19:29
  • Thanks guys for your responses. When you say "similar", what do I have to change then? :) – SteffPoint Jul 1 '16 at 5:35
  • I've already changed it to suit your requirement. You need to change the names of "listname1", "listname2" etc. and you need to change yourdiv to whatever DOM element you want to display the final count in. – Submits Jul 1 '16 at 7:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.