Uploading multiple images I have this code which works for uploading multiple files (images). However, it seems inefficient due to having to a function for every single file upload (for 2 uploads, but there will be about 12 in total).

function readURL1(input) {
    if (input.files &amp;&amp; input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            jQuery('#div1').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

function readURL2(input) {
    if (input.files &amp;&amp; input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            jQuery('#div2').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}


Then...

jQuery("#img1").change(function(){
    readURL1(this);
});

jQuery("#img2").change(function(){
    readURL2(this);
});
No need for a loop. The only difference between the functions is the target image (I assume it's an image, since DIVs don't have a srcattribute), so change the function to get the target from an data attribute of the input field:

function readURL(input) {
    if (input.files &amp;&amp; input.files[0]) {
        var image = jQuery(input).data('image-target');

        var reader = new FileReader();

        reader.onload = function (e) {
            jQuery(image).attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}


Add those data attributes to the HTML:

Image 1: &lt;input type="file" data-image-target="#div1"&gt;
Image 2: &lt;input type="file" data-image-target="#div2"&gt;


As you may notice the id of the input fields have gone. Instead of assigning them each their own separate event handler, assign one handler for all (or use a class):

jQuery("input[type=file]").change(function() {
   readURL(this);
});