How to check for attachments or limit the number of attachments in SharePoint via jQuery

A client had a business requirement that if someone added an attachment to an item in a list, a metadata field had to be filled in.

So I put on my jQuery glasses (they are quite special, looking a bit like Dame Edna’s)

I ended up with following code which uses the PreSaveAction, a default function that runs every time you hit the “ok” button:

function PreSaveAction() {
// we create a counter and we go through the fileupload to check how many there are
  var count = 0;
  $("input[name^='fileupload']").each(function(){
  if ($(this).val() != ""){
      count++;
  }
  });
  // Then we check if the mandatory field is empty and if we have attachments
  if ($(":select[title=Contact means]").val() == “”) {
    if (count > 0){
            alert("Please fill the field if you have uploaded an attachment");
      return false;
    }
}
//if the field was not empty or we have no attachments,
//we don’t go into the if loop and we can go ahead and save the item
Return true;
}</pre>

This code could also be used to limit the number of attachments a user can add.
That code would be:

function PreSaveAction() {
// we create a counter and we go through the fileupload to check how many there are
  var count = 0;
  $("input[name^='fileupload']").each(function(){
  if ($(this).val() != ""){
      count++;
  }
  });
  // Then we check there are more then 10 attachments
    if (count > 10){
            alert("Please limit to 10 attachments");
      return false;
    }
// if we have less then 10 items, we can just continue
Return true;
}

Don’t forget to add the jquery library reference!

About: Marijn

Marijn Somers (MVP) has over 14 years experience in the SharePoint world, starting out with SP2007. Over the years the focus has grown to Office 365, with a focus on collaboration and document management. He is a business consultant at Balestra and Principal Content Provider for "Mijn 365 Coach" that offers dutch employee video training. His main work tracks are around user adoption, training and coaching and governance. He is also not afraid to dig deeper in the technicalities with PowerShell, adaptive cards or custom formatting in lists and libraries. You can listen to him on the biweekly "Office 365 Distilled" podcast.