Add or Remove File Field in jQuery

Hi guys! Today I’m going to share about multiple file upload in PHP.

We’ll be using jQuery to add or remove new file fields.

This one is useful when your system has multiple email attachment or document management feature.

"Home

This code contains the form with the file field, add and remove button and of course, the upload button. jQuery is used for its dynamic adding or removing of file fields.

<html>
<head>
     <title>How To Add or Remove File Field Then Upload File in PHP and jQuery</title>
</head>
<body>
<?php
isset($_REQUEST['action']) ? $action = $_REQUEST['action'] : $action = '';
 
if( $action == 'uploadfiles' ){
     //define where the files will be uploaded
     $upload_directory = 'uploads/';
     $x=0;  
          echo "</div>Uploaded Files:</div>";
          foreach ( $_FILES['data']['name'] AS $key => $value ){  
               echo "<div>{$value}</div>";
               //Move file to server directory
               move_uploaded_file($_FILES["data"]["tmp_name"][$x], $upload_directory . $_FILES["data"]["name"][$x]);
               $x++;  
          }
}
?>
     <form enctype="multipart/form-data" action="#" method="POST">
          <input type="hidden" name="MAX_FILE_SIZE" value="100000" />
               <div>Choose a file to upload:</div>
                    <div id="text">
                         <div ><input name="data[]" type="file" /></div>
                         <!-- This is where the new file field will appear -->
                    </div>
                    <input type="button" id="add-file-field" name="add" value="Add input field" />
                    <input type='hidden' name="action" value="uploadfiles" />
                    <input type="submit" value="Upload File" />
     </form>
 
 
 
     <script type="text/javascript" src="js/jquery-1.6.1.min.js"></script>
     <script type='text/javascript'>
          $(document).ready(function(){
                // This will add new input field
               $("#add-file-field").click(function(){
                    $("#text").append("<div class='added-field'><input name='data[]' type='file' /><input type='button' class='remove-btn' value='Remove Field' /></div>");
               });
               // The live function binds elements which are added to the DOM at later time
               // So the newly added field can be removed too
               $(".remove-btn").live('click',function() {
                    $(this).parent().remove();
               });
          });
     </script>
</body>
</html>

Download Source Code
You can download all the code used in this tutorial for only $9.99 $5.55!

Thank you for learning from our post about: Add or Remove File Field in jQuery.

By Mike Dalisay

I'm Mike Dalisay, a pro web developer since 2010. I love web development. Improving our tutorials and source codes makes me happy. Do you want to suggest an edit to our tutorial? Got something to ask about our source codes? You may use our comments section below or email our team at [email protected]

12 comments

  1. Hello Dalisay,

    Thanks for reply, i managed to send image paths to mysql database.

    I found your code lack validation for image extensions and accepts all kinds of inputs, also there is possible coalition of image. Based on these observations i successful manage to make a little modifications.

    For the first part i added:
    $name=$_FILES[“image”][“name”][$key] ;
    $oext=getExtention($name);
    $ext=strtolower($oext);
    // Assigning $name to $base_name variable for storing image path on mysql database
    $base_name=getBaseName($name);
    if($ext==”jpg” || $ext==”jpeg” || $ext==”bmp” || $ext==”gif” || $ext==”png”){

    For the second part i added:
    // Renaming image to avoid possible coalitions
    $name = rand(10000, 990000) . ‘.’ . $ext;

    But i have more but last question how can i limit input fields for accepting let say the maximum of six inputs only?

    Please Help

    1. Hello @disqus_1I7j2mAqQc, thanks for the tips! We’ll update the code above soon. About your question, you can count element by class, in our case above, it is:


      var numItems = $('.added-field').length;

  2. Hi
    I found your code very useful despite the fact that it was written 2 years ago. How to store the image path to mysql database?

    Please Help

    1. Hello @disqus_1I7j2mAqQc, glad that our post has been useful to you! About your question, you should save this part…

      $upload_directory . $_FILES[“data”][“name”][$x]

      …to a variable and then insert it to your database. The save command must be inside the foreach loop.

      We have tutorials that can help you with that, this is one: PHP & MySQL CRUD (create, read, update & delete) tutorial https://www.codeofaninja.com/2011/12/php-and-mysql-crud-tutorial.html

  3. @Braj Kishor: If you see the live demo, When you click the “Add Input Field” button, a new file field and “Remove Field” button will be added.

    The “Remove Field” button has an id of “remove-btn”. If the user clicked that button, the File field and remove button will disappear. we used jQuery “live” function here because the fields are added dynamically after loading the page.

    $(this).parent().remove(); is the code to make the container of the file field and remove button disappear.

    please search for jquery live() and parent(). :)

  4. $(“.remove-btn”).live(‘click’,function() {
    $(this).parent().remove();
    i don’t understand this line that how it does it work,please confince me theoratically in words please…

  5. Very Nice and simple good work, I am still a newbie at web development and I have a question where you have , well when I go and view source using my browser after adding an extra file upload box I dont see any extra file upload boxes added, in the source?
    Joe

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back to top