As others have mention, don't reuse id
s, instead use a class
.
The easiest way to store data about an element is to just create a property on that element.
In jQuery, this
in the callback function references the element itself, so here we just give this
a property of click_count
and then increment that every time the link is clicked.
jQuery('.extLink').click(function(event) {
event.preventDefault(); //just for this example, remove for production
this.click_count = (this.click_count ?? 0) + 1;
//Qualtrics.SurveyEngine.setEmbeddedData("clicked", this.click_count); //uncomment this for production
jQuery(this).siblings('span').text(this.click_count); //remove this for production too
jQuery('#NextButton').click();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div><a href="https://www.directrelief.org/" class="extLink" rel="noopener" target="_blank">Direct Relief</a> - <span>0</span> - Support for people affected by emergencies</div>
<div><a href="https://water.org/" class="extLink" rel="noopener" target="_blank">Water.org</a> - <span>0</span> - Provision of safe and accesible water</div>
<div><a href="https://www.feedingamerica.org/" class="extLink" rel="noopener" target="_blank">Feeding America</a> - <span>0</span> - Works on hunger relief</div>
Although the challenge with this approach for this scenario is that the client also has access to the element properties, so they could changed click count
to whatever they want, which would have unintended consequences.
Since we're using jQuery, a great work around to this is to use the .data() method. This allows us to store data with the element, with the benefit that the client has no access to it.
jQuery('.extLink').click(function(event) {
event.preventDefault(); //just for this example, remove for production
let $link = jQuery(this);
$link.data('click_count', ($link.data('click_count') ?? 0) + 1);
//Qualtrics.SurveyEngine.setEmbeddedData("clicked", this.click_count); //uncomment this for production
jQuery(this).siblings('span').text($link.data('click_count')); //remove this for production too
jQuery('#NextButton').click();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div><a href="https://www.directrelief.org/" class="extLink" rel="noopener" target="_blank">Direct Relief</a> - <span>0</span> - Support for people affected by emergencies</div>
<div><a href="https://water.org/" class="extLink" rel="noopener" target="_blank">Water.org</a> - <span>0</span> - Provision of safe and accesible water</div>
<div><a href="https://www.feedingamerica.org/" class="extLink" rel="noopener" target="_blank">Feeding America</a> - <span>0</span> - Works on hunger relief</div>