Imagine I try to achieve this :
A user will see the result of his finished uploaded photo, If the first image existed, attach to the second block, and so on. But my code below has flawed, it attached one photo to all div. What's wrong with my logic?
$("#photo_area div").each(function(i, obj) {
i++;
var stopLoop = false;
if (!$(obj).attr('style') && stopLoop == false) {
$(obj).attr('style', 'background:url(http://example.com/' + encodeURI(data.file_name) + ') no-repeat center center');
$('input[name="photos' + i + '"]').val(encodeURI(data.file_name));
stopLoop = true;
}
});
My DOM
<div id="photo_area">
<div></div>
<div></div>
<div></div>
<div></div>
<input type="hidden" name="photo1">
<input type="hidden" name="photo2">
<input type="hidden" name="photo3">
<input type="hidden" name="photo4">
</div>
I've created an example,using color as example : https://jsfiddle.net/m4orLzpr/
If you want to stop the loop when an image on the list is not uploaded, you can do this by writing an else statement for the if condition and moving stopLoop=true; to the else statement and moving var stopLoop=false; outside the loop. Otherwise, there is no use of the stopLoop variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With