2

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

Rod Xavier
  • 3,983
  • 1
  • 29
  • 41
Coeus
  • 2,385
  • 3
  • 17
  • 27
  • http://stackoverflow.com/questions/6276835/onclick-event-pass-li-id-or-value . can also refer http://stackoverflow.com/questions/27523379/getting-selected-item-from-ul-li-jquery –  Jul 28 '16 at 06:58

2 Answers2

3

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 to prevent undesired bugs. 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()
arogachev
  • 33,150
  • 7
  • 114
  • 117
1

In your template, you're giving every <span> element the same identifier (item_cat_name). Your second jQuery selector selects all <span> elements with that identifier.

To resolve this, change your jQuery to something like:

$('li').on('click', function () {
   alert($(this).children('span').text())
});

This would only show the texts of <span> elements directly below the clicked <li> element (using $(this) is the key here).

Also, I would advise to give every <span> element an unique identifier, e.g. the primary key of the ThemeCategory; so that you can then base your further actions on that.

mhkuu
  • 91
  • 4