0

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.

4 Answers 4

4

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)
    }); 
});
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect solution! Have been scratching head over this since yesterday. Thank you so much!
What if there are 2 images with different "id" so how would we select ?
2

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.

Comments

1

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);
    }); 
});

Comments

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

1 Comment

echo sprintf() is an "antipattern". There is absolutely no reason that anyone should ever write echo sprintf() in any code for any reason -- it should be printf() without echo every time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.