Search code examples
jqueryhtmljsrender

How to toggle only the clicked element while using jsrender scripts?


This is my HTML code:

<li>
    <div class="search-res-title clearfix">
          <h3> <a href="food-details.html?item={{>_source.name}}" > {{>_source.name}}</a> </h3> <span><i class="badge">{{>_source.items.length}}</i>Places</span> 
          </div>

        <ul class="sr-itemlist">
        {{for _source.items}}
                <li> <a href="restaurant-page.html?restaurant={{>hotelDetails.key}}" > {{>hotelDetails.name}}</a> <i class="badge">{{>hotelDetails.misc.rating}}</i> </li>
        {{if #index ==2}}
         </ul>
        <div class="item-serh-more test{{:#index}} extra-list clearfix" >
            <ul class="sr-itemlist">
        {{/if}}
        {{/for}}
            </ul>
        {{if _source.items.length >=2 }}
        </div>
        {{/if}}
        <a href="#" class="loc-showbtn" refVal="{{:#index}}">more<span class="caret"></span></a>
    </li>
</script>

Now, this is my jQuery code

var showMore = function () {
 $('body').on('click', '.loc-showbtn', function () {
  $('.item-serh-more').toggle();
    });
  };

What I want is: When I click the ".loc-showbtn" i want individual element to open.

What happens now is: When I click the ".loc-showbtn",the entire elements with class " $('.item-serh-more').toggle();" opens up.

I tried giving index number of the jsrender loop to the class ".item-serh-more". But it seems not working.


Solution

  • The div required for toggling is the previous sibling of clicked anchor. you can simply use .prev() with clicked elements context this to target it:

    $('body').on('click', '.loc-showbtn', function () {
      $(this).prev().toggle(); 
    });