Ad

Django Button Class Forloop Trigger Javascript

- 1 answer

i have forloop in Django template and want to make button for elements if condition contains true to show additional info as infobox, or popup. Best way to do this is javascript, but how to trigger each one separately? I dont know how many buttons will be. I could use forloop counter, but how to activate js then?

{% for hist in histor %}
<a class="trigger_popup_{{ forloop.counter }}"><img src='{% static "images/info.PNG" %}'></a>
{% if hist.ikona == 1 %} <img src='{% static "images/hist/108.png" %}'>
{% elif hist.ikona == 2 %} <img src='{% static "images/hist/154.png" %}'>
{% elif hist.ikona == 8 %} <img src='{% static "images/hist/499.png" %}'>
{% endif %}
{% endfor %}

What to add in this:

var modal = document.getElementById("trigger_popup_");

button / link class may be trigger_popup_4, trigger_popup_5, trigger_popup_88 How to manage this?

Ad

Answer

one of the possible solution would be using data attributes in element with event handlers

{%for i in list%}
  <a target="_blank" rel="nofollow noreferrer" href="javascript:void(0);" data-id="{{i.id}}" class="triggermodal">somelink</a>
{%endif%} 

<script>
  $("body").on("click",".triggermodal",function(){
    var modalid=$(this).attr("data-id");
    $("trigger_popup_"+modalid).modal("toggle");/toggles the modal
  });
</script>
Ad
source: stackoverflow.com
Ad