Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I have Library on which I have created a ribbon button. On click of the button I am trying to identify if the selected item is a folder or a file. below if the code snippet that I am using:

var context = SP.ClientContext.get_current();
var web = context.get_web(); 
var items = SP.ListOperation.Selection.getSelectedItems(context); 
var currentLibrary = web.get_lists().getById(SP.ListOperation.Selection.getSelectedList(context)); 
var index;
for (index in items) {
    var selectedItem = currentLibrary.getItemById(items[index].id);
    // Need to identify if 'selectedItem' is folder or not
    console.log("FileSystemObjectType = " + selectedItem.FileSystemObjectType); // Returns 'undefined'
    console.log("get_file = " + selectedItem.get_file()); // Returns 'SP.ListItem' object
    console.log("get_folder = " + selectedItem.get_folder()); // Returns 'SP.ListItem' object
}

Taking reference from this link I tried to use FileSystemObjectType but in my case it ends up showing undefined for both file and folder. Also if I try to check if the selected item is a file or folder using below code it always return true.

if(item.FileSystemObjectType == SP.FileSystemObjectType.Folder) {
    // Always returns true
}

What am I doing wrong here? How can I identify if the selected item in Library is a file or a folder?

share|improve this question

1 Answer 1

up vote 3 down vote accepted

Your example contains the following errors/typos:

To get fs object type use the following syntax:

var fsObjType = selectedItem.get_fileSystemObjectType();

Another point is, ListItem object have to be requested first before getting it's value, this is why in your example it will not work.


In fact, you don't have to request ListItem object in order to determine its type using SP.ListItem.fileSystemObjectType Property.

SP.ListOperation.Selection.getSelectedItems() Method returns an array of objects, for example: [{"id" 1: ,"fsObjType": "0"}] , where fsObjType specifies file system object type, the following example demonstrates how to determine the type of selected object.

Example

var context = SP.ClientContext.get_current();
var web = context.get_web(); 
var selItems = SP.ListOperation.Selection.getSelectedItems(context); //not SP.ListItem collection!
for (var index in selItems) {
    var selItem = selItems[index];
    switch(selItem.fsObjType){
        case "0":
          console.log('File has been selected');
        break;
        case "1":
          console.log('Folder has been selected');
        break;
    }
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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