0

Thanks to this question, I learned how I can dynamically create HTML elements based on a user's selected option.

Now, when users select an option of, say, 5, five input field groups are created and shown.

For each input field group, there exists a file upload button for images.

I have a javascript function that detects when users upload an image and then displays a thumbnail of that image.

The problem is that I need to access the ID of each <input type="file" id="appraisal_image1">

I could, of course, create multiple function definitions, each with different ID's, and then call each of those functions, but I was wondering if there was accomplish this without copying & pasting so much code.

I've attached a jsFiddle that correctly displays the first and second image thumbnails but not subsequent ones since there are no functions defined or called for the rest.

3 Answers 3

2

Instead of using ids use classes and use event delegation to register the change handler

In the below sample additional classes appraisal_image is added to the file input control where as the class thumbnail_image is added to the image element

Try

// Show Thumbnail
function getThumbnail (input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $(input).closest('.image-ct').find('.thumbnail_image').attr('src', e.target.result).show();
        }

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

$('#Number').change(function() {
    var num = parseInt($(this).val(), 10);
    var container = $('<div />');
    for(var i = 1; i <= num; i++) {
        container.append('<div class="image-ct ' + i + '"><div class="row"><div class="col-md-6 col-md-offset-3 bottom-15"><label for="file" class="text-center" id="imageNumber' + i + '">Upload Image:</label><input class="light-gray center appraisal_image" type="file" name="appraisal_image' + i + '" id="appraisal_image' + i + '"><br><div class="image-holder"><img class="hide-till-uploaded center thumbnail_image" id="thumbnail_image' + i + '" src="#" alt="your image" /></div></div></div><div class="row"><div class="col-md-2 col-md-offset-5 bottom-15"><label for="Size" id="Size' + i + '">Size</label><input type="text" class="form-control" name="Size' + i + '" placeholder="Rug Size" id="Size' + i + '"></div></div></div>');
    }

    $('#here').empty().append(container);
});
$('#here').on('change', '.appraisal_image', function(){
    getThumbnail(this);
})

Demo: Fiddle

Sign up to request clarification or add additional context in comments.

3 Comments

Wow, I will have to spend some time to look into exactly how this works, but I am amazed! I was beginning to think I was going to have to copy and paste a lot of code. Thanks for your help!
Is there a way to have the anonymous function called on the page load in addition to on change. That way, at least one input field will be created.
Thanks. I see the .change(); at the end of the function. Interesting!
1

You can use this code to get all ids of input type that exist in your form

[].forEach.call(document.querySelectorAll("input[type='text']"),
           function (input) {
               var value = input.value;
               var id = input.id;
               alert(id);
           });

Comments

0

Use classes instead of ids and then you can use jQuery's on delegate:

$(".appraisal_image")  // get all elements with this class
   .on("change", function(){
       getThumbnail1(this);
       $(this).css("display", "block");
   });

on will add events to elements that don't exist yet. This means that elements that are dynamically added will automatically be assigned the event

about: jquery on

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.