Reputation: 725
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);
});
});
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
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
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