Raphael Rafatpanah
Raphael Rafatpanah

Reputation: 19967

How to Dynamically Define & Call jQuery Functions

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.

Upvotes: 0

Views: 90

Answers (3)

monu
monu

Reputation: 370

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);
           });

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

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

Upvotes: 2

jasonscript
jasonscript

Reputation: 6170

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

Upvotes: 0

Related Questions