Luke Luke - 26 days ago 9
Javascript Question

getElementByID for Dynamically generated ID Elements

I am having an issue with getting the value of an

ID
element of the item that is dynamically generated from the data obtained from the database. I have a query
SELECT ItemID, ItemName, ItemImageName FROM Items
. Than I have the following code that will generate
ID
for each
<div>
for all rows returned from the database by concatenating the value of
ItemID
to each ID name.

for ($i=0; $i <$numrows; $i++) {
$stmt->fetch()

<div> <img class="itemImage" id="Image" .$ItemID src=/images/itemImage . $itemID> $ItemID </div>
<div id= "ItemID" .$ItemID> $ItemID </div>
<div id= "ItemName" .$ItemID> $ItemName" </div>

}


This should return a similar result to this for an item with
ItemID=002
:

<div> <img class="itemImage" id=Image002 src=/images/Image002 > </div>
<div id= ItemID002> 002 </div>
<div id= ItemName002> SomeNameOfItem002" </div>


Then I want to be able to click an image with an
ID=Image002
and I want to get a value of
ItemID
with the
getElementById("ItemID").innerHTML
. I have the following code:

var itemID = document.getElementById("ItemID").innerHTML;

$( ".itemImage" ).click(function() {
var itemID= document.getElementById("ItemID").innerHTML;
console.log(itemID);


This however returns
itemID
as undefined. Any help would be greatly appreciated!

Answer Source
        <div> <img class="itemImage" id=Image001 src="/images/Image001"> </div>
        <div id=ItemID001> 001 </div>
        <div id=ItemName001> SomeNameOfItem001" </div>

        <div> <img class="itemImage" id=Image002 src="/images/Image002"> </div>
        <div id=ItemID002> 002 </div>
        <div id=ItemName002> SomeNameOfItem002" </div>

        <div> <img class="itemImage" id=Image003 src="/images/Image003"> </div>
        <div id=ItemID003> 003 </div>
        <div id=ItemName003> SomeNameOfItem003"> </div>

        <script>
            $(document).ready(function () {
                $(".itemImage").click(function () {
                    var imgID = $(this).prop('id').replace("Image", "");
                    // you can directly use value imgID variable if its same. or you 
                    //can use from ItemID inner html
                    var yourValue = $("#ItemID" + imgID).html();
                    alert(yourValue);
                })
            });

        </script>