Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
0 like 0 dislike
2.4k views
in SharePoint Server by 2 3 4
i am working with SharePoint list and i want to get the current list and the count of elements in this list , using java script

note that i am using SharePoint 2016

1 Answer

1 like 0 dislike
by 6 6 9
edited by

Add the below code in script editor web part to

Get Current SharePoint List Name in JS

<script type="text/javascript">
SP.SOD.executeFunc("sp.js", "SP.ClientContext", function () {
     SP.SOD.executeFunc("sp.core.js", "SP.ListOperation.Selection",
         function () {
        var listId = SP.ListOperation.Selection.getSelectedList();
         if (typeof (listId) == "undefined" || listId == null || listId == "") {
             return;
        }
         var ctx = SP.ClientContext.get_current();
        var list = ctx.get_web().get_lists().getById(listId);
        ctx.load(list);
         ctx.executeQueryAsync(
             Function.createDelegate(this, function (sender, args) {
                 alert(list.get_title());
             }),
            Function.createDelegate(this, function (sender, args) {
             alert(args.get_message());
            })
         );
     });
 });
</script>

Get SharePoint List Item Count in JS

<script type="text/javascript">
    var clientContext = null;
    var web = null;
    ExecuteOrDelayUntilScriptLoaded(Initialize, "sp.js");
    function Initialize()
    {
        clientContext = new SP.ClientContext.get_current();
        web = clientContext.get_web();
        var list = web.get_lists().getByTitle("ListName");
        var camlQuery = new SP.CamlQuery();
        var q = "<View><Query><Where><Eq><FieldRef Name='FieldName' /><Value Type='Integer'>5</Value></Eq></Where></Query><RowLimit>0</RowLimit></View>";
        camlQuery.set_viewXml(q);
        this.listItems = list.getItems(camlQuery);
        clientContext.load(listItems, 'Include(Id)');
        clientContext.executeQueryAsync(Function.createDelegate(this, this.onListItemsLoadSuccess), 
        Function.createDelegate(this, this.onQueryFailed));
    }
    function onListItemsLoadSuccess(sender, args) {

        var count = this.listItems.get_count();

        alert(count);
    }

    function onQueryFailed(sender, args) {
        alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
    }
</script>
If you don’t ask, the answer is always NO!
...