Home jQuery

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>jQuery Add or Remove File Field Then Upload File in PHP and jQuery

Multiple file upload

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.

Before you write a comment, please read this guide and our code of conduct.
12 replies
  1. Anonymous
    Anonymous says:

    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

  2. Mike Dalisay
    Mike Dalisay says:

    @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(). :)

  3. Germano
    Germano says:

    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

    • Mike Dalisay
      Mike Dalisay says:

      Hello @disqus_1I7j2mAqQc:disqus, 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;

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

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