Document library: script to update Title from Filename

I got a request for a script that updates the Title field to be the same as the Name field in a document library. This to be able to use a lookup column to pick relevant documents from another list or library.
This code will insert a button that lets you search for all documents that do not already have a Title set, and update it to be the same as the file name.
Add this code to a list view in the library you want to update:
<input type="button" onclick="updateTitleFromName()" value="Update Title from Name" />

<script type="text/javascript" src="/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="/Scripts/spjs-utility/spjs-utility.js"></script>
<script type="text/javascript">

function updateTitleFromName(){
 var q, res, uRes, count;
 count = 0;
 q = "<Where><IsNull><FieldRef Name='Title' /></IsNull></Where>";
 res = spjs_QueryItems({"listName":_spPageContextInfo.pageListId,"query":q,"viewFields":["ID","FileLeafRef"]});
 if(res.count === 0){
  alert("No files without title found.");
  return;
 }
 if(!confirm("There are "+res.count+" files to update. The page will appear as frozen while the script is working.\n\nContinue?")){
  return;
 }
 $.each(res.items,function(i,item){
  uRes = spjs_updateItem({"listName":_spPageContextInfo.pageListId,"id":item.ID,"data":{"Title":item.FileLeafRef.split(";#")[1]}});
  if(!uRes.success){
   alert("Could not update the file: "+item.FileLeafRef+" due to the follwing error:\n\n"+uRes.errorText);
  }else{
   count += 1;
  }
 });
 alert("Updated "+count+" files.");
 location.href = location.href;
}
</script>
If you want to add this code directly to the page, use a HTML form web part to hold the code. You can also use a CEWP to link to the code from another location (like a document library).

Comments