Coeus Coeus - 4 months ago 5
jQuery Question

Django- Jquery loops through all options

Im doing server side rendering with the help of Django. In my django templates Im looping through all the values obtained from my Database. In jquery while selecting a single value, JS gives me all the values obtained from database, but I wanted only selected values

Views.py

def theme(request):
context={}
context['All']=Theme.objects.all().count()

for t in ThemeCategory.objects.all():
context[t.categoryName]= t.theme_set.count()

context=collections.OrderedDict(sorted(context.items()))
return render(request,'theme-list.html',{'category_name':context})


In templates

<ul class="pick-tags" >
{% for category_name,count in category_name.items %}
<li id="item_cat">
<span id="item_cat_name">{{ category_name }}</span>
</li>
{% endfor %}
</ul>


In jquery Im selecting the required value

$('li#item_cat').on('click', function () {
alert($('span#item_cat_name').text())
})


But instead of giving me a single value, It me all the value obtained from DB.

How should I get only one value when click on
<li>


Any help in obtaining selected value would be helpful

Answer

First of all, id of each HTML element should be unique. And you are creating multiple li and span elements with the same id. Make sure it's unique, it's better to use class and data attributes if needed.

Second, you need to get text of selected element, not any element, so you need to use this:

$(this).find('span').text()
Comments