SCC
SCC

Reputation: 87

Select an element's id from PHP loop using jQuery

I have a list of <img> tags with each of them contains different id. This is done using PHP for loop as shown below:

<?php
   for($n=0; $n<=5; $n++)
   {    
?>          
      <img id="<?php echo 'time_'.$n; ?>" src="$output-mp4_thumbnails-$n.jpg">
<?php
   }
?>

I want to use jQuery in such a way that, when I click on the specific image on my browser, it would print out the id accordingly. Below is how I code it:

$(document).ready(function () {
    $("img").click(function () {
       alert($("img").attr("id"));
    }); 
});

However this keeps printing only the first id, which is time_0. I have been looking around for ways to solve this, and I found out about change(), but it can only be used for form inputs.

Any suggestions will be greatly appreciated.

Upvotes: 0

Views: 240

Answers (4)

Sidstar
Sidstar

Reputation: 354

for($n=0; $n<=5; $n++) {
    echo sprintf("<img id='time_%d' src='%s-mp4_thumbnails-%d.jpg' />", $n, $output, $n);
}

Upvotes: 0

vee
vee

Reputation: 38645

You're nesting php tags <?php and ?>, specifically in the loop.

Try to echo out the image tag as:

for($n=0; $n<=5; $n++)
{               
    echo "<img id='time_{$n}' src='{$output}-mp4_thumbnails-{$n}.jpg' />";
}

This should generate unique image ids as time_0, time_1 and so on upto time_5. In addition to this, you also need to incorporate either @Arun's answer or @tchow002 answer on the jQuery side as:

$(document).ready(function () {
    $("img").click(function () {
       alert(this.id)
    }); 
});

Upvotes: 4

Arun P Johny
Arun P Johny

Reputation: 388446

you have a problem with the alert, you have alert($("img").attr("id")) which will always alert the id of the first img element, instead you need to alert the id of the clicked element so alert(this.id)

$(document).ready(function () {
    $("img").click(function () {
       var $id = this.id;
       alert(id);
    }); 
});

Upvotes: 1

tchow002
tchow002

Reputation: 1098

Try this alert($(this).attr("id"));

this will select the img that was clicked. Your current code matches the first img instead and does not account for what was clicked.

Upvotes: 2

Related Questions