jQuery Question

How to check every div block for image

How to check every block for image, and if it is empty, load image inside.

My try:

function showFile(e) {
var files = e.target.files;
var a = 1;
for (var i = 0, f; f = files[i]; i++) {
if (!f.type.match('image.*')) continue;
var fr = new FileReader();

fr.onload = (function(theFile) {

return function(e) {

$('.tra').each( function() {
var $this = $(this);
if ( $this.find('img').length === 0 ) {
$this.append('<img src="'+e.target.result+'">');
} else {
alert("You can select only 5 images");
}
});
};
})(f);

fr.readAsDataURL(f);
}
}

document.getElementById('photo').addEventListener('change', showFile, false);


After upload image, i want to show this image:

html:

<div class="tra full_photo">
</div>
<div class="tra mini_photo">
<div class="tra block_mini_photo block_mini_photo2"></div>
<div class="tra block_mini_photo block_mini_photo3"></div>
<div class="tra block_mini_photo block_mini_photo4"></div>
<div class="tra block_mini_photo block_mini_photo5"></div>
</div>
<form>
<input type="file" name="photo[]" id="photo" class="upload_true" accept="image/jpeg,image/png,image/gif" multiple>
</form>


But after loading, all the blocks are filled
jsfiddle

Answer

You shold do this:

return function(e) {

        var tra = $('.tra');
        var one = false;

        // test each single div
        tra.each(function(){
            if($(this).find('img').length <= 0 && !one){
              $(this).append('<img src="'+e.target.result+'">');
              one = true;
            }
        });

        if(!one){
            alert("You can select only 5 images");
        }

    };