serii
serii

Reputation: 5

Jquery changing images on on click

i have a problem with my click changing image, i have database messages , every message has a status 0 or 1 , from my code o have to click on status image and it will change, its changes BUT only for the first Message. When i click to other message status it not changes but changes only for the first status. how can i go this run!!!

<script type="text/javascript">
 $(function() {
$('.imageCheck').click(function(e){
 e.preventDefault();
$("#bg").attr('src',"/application/admin/img/tick.png");  
});    
});

    </script>    

                                            <th>Status</th>

                </tr>
            </thead>
            <tbody>
                <?php 
                foreach ($users as $user):

                ?>
                <tr>
                    <td><?=$user['id']?></td>
                    <td>                                                      
  <div class="imageCheck"><img id="bg" src="<?php echo $img_path;?>publish_x.png" name="statusCheck" value="0" />
                                                   </div>                                                     
                                            </td> 

Upvotes: 0

Views: 246

Answers (3)

Connor Ross
Connor Ross

Reputation: 355

Ids are supposed to be unique on a page. Since you are looping you are going to have multiple imgs with id bg, so only the first one works.

as BenM states change it to .bg also update your code to find the exact image below the div

$(".bg", $(this)).attr('src',"/application/admin/img/tick.png"); 

Upvotes: 0

Samich
Samich

Reputation: 30105

You need to change the #bg in the your message control. In event handler use find to get nested bg element.

$('.imageCheck').click(function(e){
   e.preventDefault();
   $(this).find("#bg").attr('src',"/application/admin/img/tick.png");  
});  

Upvotes: 1

BenM
BenM

Reputation: 53198

Because an ID can (or rather should) only exist once in the DOM. jQuery is only changing the first element that matches the selector #bg. Try using a class instead:

<img class="bg" />

$('.bg').attr('src', '...');

Upvotes: 0

Related Questions