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!