Coeus Coeus - 4 years ago 86
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

def theme(request):

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

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>
{% endfor %}

In jquery Im selecting the required value

$('li#item_cat').on('click', function () {

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

Any help in obtaining selected value would be helpful

Answer Source

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download