Jake Nguyen
Jake Nguyen

Reputation: 71

How to pass <img> value on click?

I'm working on a project where there are tiles of different pictures and I want to pass the value to another page when an image is clicked on. Since <img> doesn't have a value attribute, I tried to wrap an <a> tag around the image as follows, although it does the job, the format of the image is messed up. Is there a better way to do this that doesn't mess with the format of the image? Thank you for your help.

<a href="results.inc.php?value=gpu" onclick="post">
  <img src="https://via.placeholder.com/200.jpg" alt="" class="cardImg">
</a>

Upvotes: 1

Views: 735

Answers (1)

Igor Lima
Igor Lima

Reputation: 317

Based on your comment, the most "harmless" way to do it would be JavaScript, adding a custom attribute to the image for the value you want it to pass in the onClick method.

document.addEventListener("DOMContentLoaded", function() {
               var allCards = document.querySelectorAll(".cardImg");
               for(i = 0; i < allCards.length; i++) {
                   var value = allCards[i].getAttribute("data-card-value");
                   allCards[i].addEventListener("click", function() {
                       document.location.href = "results.inc.php?value=" + value;
                   });
               }
            });
.cardImg {
  cursor:pointer;
}
<img src="https://via.placeholder.com/200.jpg" data-card-value="gpu" alt="" class="cardImg">

Upvotes: 1

Related Questions