5
\$\begingroup\$

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 && 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 && 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);
});
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

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 && 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: <input type="file" data-image-target="#div1">
Image 2: <input type="file" data-image-target="#div2">

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);
});
\$\endgroup\$
1
  • \$\begingroup\$ Thank you. Much better! Saved quite a few lines of code. I knew I was missing something but jQuery isn't my strongest. Nice one! \$\endgroup\$
    – user43251
    Jun 2, 2014 at 12:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.