Get id attribute number in <img> tag within while cycle

Asked

Viewed 83 times

0

The problem is this: I have a while cycle on PHP and I need to get the value of an attribute id within a tag img. This value is dynamic because it assigns you a variable PHP.

$getLastFour = mysqli_query($dbc,"Select * From products Order By id_product DESC LIMIT 4") or die(mysqli_error($dbc));
while($row = mysqli_fetch_array($getLastFour)){
        $idProd = $row["id_product"];
        $name = $row["name_Product"];
        $price = $row["prod_price"];
        $description = $row["prod_description"];
        $idImage = $row["img_id"];

?>
                            <div class="b-wrapper"><h2 class="b-animate b-from-left b-delay03 ">
                                <img src="images/link-ico.png" class="img-responsive" id="<?php echo $idImage ?>"  alt="" onclick="showId();"/></h2>
                            </div>
<?php
        }
        ?>
        <script type="text/javascript">
            function showId () {
                var id = document.getElementById('<?php echo $idImage ?>');
                var nodeList = [];
                for (var i = 0; i < id.length; i++) {
                    nodeList[i] = id[i];
                }
                alert(nodeList[i]);
            }
        </script>

The problem is how the idwill receive different values, when fetching the value with javascript this returns "Undefined".

1 answer

1


Just pass the element as parameter for the method:

function showId(el) {
  alert(el.id);
}
<img src="http://aux.iconpedia.net/uploads/iphone-bk-icon-64.png" id="um" onclick="showId(this);">


<img src="http://aux.iconpedia.net/uploads/1971286922493102958.png" id="dois" onclick="showId(this);">


<img src="http://aux.iconpedia.net/uploads/16965988981513619283.png" id="tres" onclick="showId(this);">

  • Thank you! I was complicating what was easy!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.