I have a html file as bellow:
<div id="preview_updated_notifications">
{% for lst in unread_list %}
<div >
<span data-notification-item="{{ lst.id }}" id="_mark_as_read_id"> ●</span>
</div>
{% endfor %}
</div>
and in js file:
$(document).on('click', "#_mark_as_read_id", function() {
var object_id = $('#_mark_as_read_id').data('notification-item');
console.log('--------------object_id:------------')
console.log(object_id)
console.log('--------------------------')
$.ajax({
type: "GET",
url: "{% url '_mark_as_read' object_id %}",
dataType: 'json',
data: {
'object_id': object_id,
},
dataType: 'json',
success: function (data) {
$('#preview_updated_notifications').html('**TEST**');
}
});
event.preventDefault();
});
But the problem is that this always prints the latest value of loop, while I expect after clicking on each item ●
retrieve the relative id!
4
Answers
{% url '_mark_as_read' object_id %}
is a Django template tag, meaning that it gets rendered when the page first loads, so the value ofobject_id
will always be the one initially passed as context, from the view.You could use another HTML attribute, to store the update URL for each
span
, which would allow you to use the Django{% url ... %}
tag.Furthermore, as you have
id="_mark_as_read_id"
inside a for loop, every<span>
element will have the same ID. IDs should be unique. You should use a class instead, and update the selector in the click function accordingly.HTML:
jQuery:
Then in your jQuery you could access it like this:
in
many spans are rendered, and each of them has the same
id
.id
should be unique in HTML, that is why only one span response to you.Ignoring the issue of the non-unique IDs you can delegate like this instead
You are using django
for loop
for html only, the javascript code also needs to be in yourfor loop
like this:{{ lst.id }}
. So the id’s will be like (_mark_as_read_id1
,_mark_as_read_id2
,_mark_as_read_id3
, ….).Now, it will get after clicking on each item
●
retrieve the relative id!