How to display specific number of image in a javascript loop

Hi,

This code work well in PHP but it’s not applying to javascript. How can I get it worked?


default_image = document.getElementById(default_image');
for(i = 1; i <= 5; i++){
	default_img = "images/default_image.png";
	default_image.src = default_img;
}

The HTML:


<img id='default_image' src='' />

You’re missing a single quote mark, and all new variables should be preceded by the “var” declaration.

var default_image = document.getElementById('default_image');
for(var i = 1; i <= 5; i++){
    var default_img_src = "images/default_image.png";
    default_image.src = default_img_src;
}

I’m not sure that I understand what your for-loop is supposed to be doing. It doesn’t seem necessary. Can you explain what you’re trying to accomplish with it?

Also, the naming of your variables is a little ambiguous. It would be easy to confuse default_img and default_image.

Your codes only show one image.

What I’m trying to do is inserting 5 default image (same image) into a placeholder div, if there’s no image yet to display, or when my user have yet to upload their images.

The placeholder will display 5 images. It work great with PHP. But I want this done with javascript instead.

I’m looking for methods that get it done. Hope I explain clearly.

Thanks

The code ytou currently have is telling the browser to download the images but is inserting them all one after the other as the same single image in the web page instead of adding them to the page.

Yes, that’s what I’m trying to do, but its’ not working as expected.

Each time you iterate through the loop you need to create a new <img> element, see the following demo:

Work like a charm, thanks.