Dipak G.
Dipak G.

Reputation: 725

jQuery onclick not getting proper values

I am trying to get Image ALT values on click event but it's not working as it should be and displays the same value (Image ALT) on click.

Here is the code:

HTML:

<a href="//cdn.shopify.com/s/files/1/0720/9527/products/MDM02-south-east-postcode-district-map-detail-large_ee8e2826-b33b-4c77-83b2-f162df33ec33_large.gif?v=1420644155" class="product-photo-thumb" title="Map 1">
    <img id="imgVariants" src="//cdn.shopify.com/s/files/1/0720/9527/products/MDM02-south-east-postcode-district-map-detail-large_ee8e2826-b33b-4c77-83b2-f162df33ec33_compact.gif?v=1420644155" alt="Map 1">
</a>

<a href="//cdn.shopify.com/s/files/1/0720/9527/products/png_large.png?v=1420644163" class="product-photo-thumb" title="Map 2">
    <img id="imgVariants" src="//cdn.shopify.com/s/files/1/0720/9527/products/png_compact.png?v=1420644163" alt="Map 2">
</a>

Javascript / jQuery

$(document).ready(function(){
    $('.product-photo-thumb').on("click", function (e) {
      e.preventDefault();
      alert(document.getElementById("imgVariants").alt);
    });
});

>> jsFiddle link

Am I missing anything?


P.S.: I know IDs must be unique but I wanted a solution that can work even without unique IDs.

Upvotes: 0

Views: 79

Answers (3)

TechGirl
TechGirl

Reputation: 488

Here is the working example where there can be multiple elements with same ID, and yet it will work fine: JSFIDDLE

  $(document).ready(function(){
    $("body").on("click",".product-photo-thumb", function (e) {
      e.preventDefault();

      alert($(this).children("img").attr("alt"));
    });
  });

Upvotes: 2

Naeem Shaikh
Naeem Shaikh

Reputation: 15725

There are two elements with same Id(shouldnt be), remove them and you should use something like e.target

here is an working example.. http://jsfiddle.net/83cyuozz/1/

   $(document).ready(function(){
        $('.product-photo-thumb').on("click", function (e) {
          e.preventDefault();
          alert(e.target.alt);
        });
      });

Upvotes: 2

Girish
Girish

Reputation: 12127

try this code

$(document).ready(function(){
    $('.product-photo-thumb').on("click", function (e) {
      e.preventDefault();
      alert($(this).find('img').attr('alt'));
    });
});

DEMO

NOTE ID must be unique.

Upvotes: 2

Related Questions