jQuery Script called from within php While loop not working properly

441

I have a php partial page that grabs images from a MySQL database and prints them in the browser using awhile loop. A jQuery function is called when I click on one of the images - this function is supposed to grab thesrc of theimg and then alert the user what thatsrc is in a pop-up window. Thissrc should change depending on whichimg is clicked.

The resulting page is a series of images and their respective data fields, as seen in this snapshot:

enter image description here

Unfortunately, the samesrc is alerted, regardless of whichimg is clicked, and it appears to be the lastimg that was printed from the while loop.

This is the alert that pops up onimg click - it should be unique for every photo, but it's the same source currently:

enter image description here

How can I get thisimgsrc that is alerted to be unique for everyimg that is clicked?

EDIT: I should also say that, when tested outside of the while loop, this jQuery script seems to work as expected - different images that are clicked alert differentsrc attributes.

 <div id="screenings">
  <?php

    //MySQL database connection established

    ...

    while ($row = mysqli_fetch_array($result)){
      echo "<div class='img_div'>";
        echo "<img class='modal_img img_screenings' ng-click=\"vm.openModal('custom-modal-1')\" src='images/".$row['image']."' >";

        ...

      echo "</div>";
    }
  ?>
 </div>

 <modal id="custom-modal-1">
   <div >
    <div >
        <img id="popup_img" src="#">
    </div>
   </div>
   <div ></div>
</modal>

<script>
  $('.img_div').on("click", function() {
    var source = ( $('.modal_img').attr("src") );
    alert(source);
    $('#popup_img').prop('src', this.src);
  });
</script>
887

Answer

Solution:

The problem isvar source = ( $('.modal_img').attr("src") ); That will get the first src attribute of an item matching the class. But all the images have the same class. You should use$(this) inside$('.img_div').on("click", function() { to reference the clicked<div>. Tryvar source = $(this).find('img').attr('src')); which should get the<img> tag src attribute of the first img inside the clicked$(this) item.

People are also looking for solutions to the problem: php - form will not submit and I have tried all I know

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.