Javascript cannot find element by id using {{key}}
How can I access the {{key}} in my script?
Script
window.onload = jQuery(function ($) {
var duration = document.getElementById("#timerseconds{{key}}").value;
duration = 10800 - duration;
display = $("#counter{{key}}");
startTimer(duration, display);
});
HTML / DJANGO
{% for key, value in list_cooking.items %}
<li class="list-group-item">
<p>{{key}}</p>
<br></br>
<p>Seconds:</p><p id='counter{{key}}'>00</p>
<input id="timerseconds{{key}}" type="hidden" value="{{value}}">
</li>
Console
jQuery.Deferred exception: Cannot read property 'value' of null TypeError: Cannot read property 'value' of null
jquery.min.js:2 Uncaught TypeError: Cannot read property 'value' of null
at HTMLDocument.<anonymous> (main.js:78)
Rendered HTML
<li class="list-group-item">
<p>Beef</p>
<br>
<p>Seconds:</p>
<p id="#counterBeef">00</p>
<input id="timersecondsBeef" type="hidden" value="5417">
</li>
VIEW
time_since = AddCooking.objects.raw("select * from heatcook_addcooking where time_start > now() - interval '180 minutes'")
for item in time_since:
list_cooking[item.foodfk.name] = (int((time_now - item.time_start).total_seconds()))
Solution:
Use inside the for loop
{% for key, value in list_cooking.items %}
<script>Script here</script>
<li class="list-group-item">
<p>{{key}}</p>
<br></br>
<p>Seconds:</p><p id='counter{{key}}'>00</p>
<input id="timerseconds{{key}}" type="hidden" value="{{value}}">
</li>
{{key}}is not defined outside the for-loop. You'll rather have to select elements using class names, rather than IDs.