Rpatillo
Rpatillo

Reputation: 1

How to select multiple images in PHP foreach loop with simple JavaScript?

I've got a project in my school and I need to build a web site only with HTML/CSS/JS (no framework).

I'm looking to build modal boxes (Modal box on w3schools) for an image gallery. My idea is to "highlight" the selected (on click) image and to show comments in that so called modal box.

The main problem is that this code works with ID, which seems (after quick researches) to be unique ... I've tried many things but I'm unable to find a decent way to manage this code.

How to handle this foreach loop and be able to select each different images?

Here is a bit of my code:
HTML:

$result = $auth->printPic($_SESSION['auth']);

foreach($result as $post) {
echo '<img name="myBtn' . $post->id . '" src="' . $post->photo . '" />';
echo '<div id="myModal" class="modal">';
echo '<div class="modal-content">';
echo '<span class="close">x</span>';
echo '<img src="' . $post->photo . '" />';
echo '</div>';
echo '</div>';
}

CSS remains the same as w3schools one.

JS I've tried this (other part is the same as w3schools):

var eles = [];
var inputs = document.getElementsByTagName("img");
for(var i = 0; i < inputs.length; i++) {
    if(inputs[i].name.indexOf('myBtn') == 0) {
        eles.push(inputs[i]);
    }
}

which seems to find my img properly. But I can't find a way to make it work.

Thanks in advance. I can put more code but my thought was to be the "clearest possible".

EDIT

Thanks to The One and Only ChemistryBlob I've found a way to deal with my problems. I've added some names/class and made loops like this one:

for (i = 0; i < pict.length; i++){
    (function(i){
        pict[i].onclick = function() {
            divimg[i].style.display = "block";
        };
    }(i));
}

Thanks for everything!

Upvotes: 0

Views: 596

Answers (0)

Related Questions