1

My equals selector is only selecting the first item on my list. It doesn't matter which image I click, it always sets my jQuery variables to the first item. Thanks!

//PHP

<div class="imgContain">
<img id="finalimg" alt="first" src="website.com/imga546.jpg">
<img id="finalimg" alt="second" src="website.com/imga645.jpg">
<img id="finalimg" alt="thrid" src="website.com/imga6786.jpg">
<img id="finalimg" alt="4th" src="website.com/imga31234.jpg">
</div>


//jQuery   
$('.imgContain').on("click", "img", function () {
         var srcc = $('img[id="finalimg"]').attr('src');
         var linkU = $('img[id="finalimg"]').attr('alt'); 

       });
tim
  • 9,896
  • 20
  • 81
  • 137

3 Answers3

1

Since id must be unique, you need to use class instead:

<div class="imgContain">
    <img class="finalimg" alt="first" src="website.com/imga546.jpg">
    <img class="finalimg" alt="second" src="website.com/imga645.jpg">
    <img class="finalimg" alt="thrid" src="website.com/imga6786.jpg">
    <img class="finalimg" alt="4th" src="website.com/imga31234.jpg">
</div>

then you can use . to target elements by class as well as using $(this) to get reference to current clicked image with class finalimg:

$('.imgContain').on("click", ".finalimg", function () {
    var srcc = $(this).attr('src');
    var linkU = $(this).attr('alt'); 
});

Fiddle Demo

Felix
  • 37,892
  • 8
  • 43
  • 55
  • ID needn't be unique. I think jQuery handles it properly. Check this fiddle: http://jsfiddle.net/txvv2/1/ – John Bupit Apr 22 '14 at 16:04
  • No, `id` must be unique: http://stackoverflow.com/questions/9454645/does-id-have-to-be-unique-in-the-whole-page. Your code work because you're applying `$(this)`. – Felix Apr 22 '14 at 16:09
0

You get Unique ID of image on its click and do manipulation as follows
Working fiddle demo http://fiddle.jshell.net/8kmdt/

<div class="imgContain">
<img id="img1" alt="first" src="website.com/imga546.jpg">
<img id="img2" alt="second" src="website.com/imga645.jpg">
<img id="img3" alt="thrid" src="website.com/imga6786.jpg">
<img id="img4" alt="4th" src="website.com/imga31234.jpg">
</div>
then change your jQuery code to:

$('.imgContain').on("click", "img", function () {
var getID=$(this).attr("id");
  var source = $("#"+getID).attr('src');
  var linkOfImg = $("#"+getID).attr('alt'); 
});
Pratik Joshi
  • 11,485
  • 7
  • 41
  • 73
-1

element id's need to be unique. you should use classes instead.

Adunahay
  • 1,551
  • 1
  • 13
  • 20
  • ID needn't be unique. I think jQuery handles it properly. http://jsfiddle.net/txvv2/1/ – John Bupit Apr 22 '14 at 16:06
  • regardless, its bad form to have multiple elements with the same id. In fact, [W3 says that an ID "must be unique in a document"](http://www.w3.org/TR/html401/struct/global.html#h-7.5.2) – Adunahay Apr 22 '14 at 16:12