Professional Documents
Culture Documents
How To Check For Attachments or Limit The Number of Attachments in SharePoint Via Jquery
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 Ednas) I ended up with following code which uses the PreSaveAction, a default function that runs every time you hit the ok button:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
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 dont 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
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; }
15 16
Dont forget to add the jquery library reference!