Friday, October 15, 2010

JavaScript find form fields type=file and remove from form if empty when submit

 Following situation. You have a form that should upload files to your server. The user should be able to set a file in the input field file or not. If the file is not set you don't want the form to send the parameter.

This text describes how you can check these file input fields with JavaScript and in case remove them from the form before it gets send.

The form HTML code:
<form action="myurl.com" enctype="multipart/form-data" id="form1" method="post">
<input name="text1" type="text" />
   <input name="text2" type="text" />

   <input name="field1" type="file" />


   <input name="field2" type="file" />
   <input name="field3" type="file" />
   <input onclick="checkFileFields();" type="submit" value="Execute" />
</form>

Put this JavaScript funtion in between the <head></head>-tags:
<script language="javascript">
function checkFileFields()
{
   //get the form with the id form1
   var form = document.getElementById("form1");
   //get all elements in the form, e.g. the input fields
   var formElements = form.elements;
   //initialize an array that stores all the elements that later get deleted, don't delete when you find the element, otherwise you change the formElements array size and miss another field
   var toDeleteElements = [];
   
   for (x in formElements)
   {
      //each element that has type='file' and value is 0 is what we want to delete later
      if(formElements[x].type=='file'&&formElements[x].value.length==0)
      {
         toDeleteElements.push(formElements[x]);
 
      }
   }
   
   for (x in toDeleteElements)
   {
      //remove element from its own parent
      toDeleteElements[x].parentNode.removeChild(toDeleteElements[x]);
   }
}
</script>

0 comments:

Post a Comment