Sarath TS
Sarath TS

Reputation: 2462

get data-attribute value in jquery

I have two categories "1 & 2". My sample code are given below. I don't know how can I get values means categories in jQuery. Please help me to get values in "getData:"

HTML

<div class="row">
            <div class="col-md-12">
                <section>
                    <div class="tag-handler-category" data-category="1">#KEYSKILLS</div><br>
                    <ul class="tag-handler">
                    </ul>
                </section>
            </div>
        </div>
        <div class="row">
            <div class="col-md-12">
                <section>
                    <div class="tag-handler-category" data-category="2">#INTERESTS</div><br>
                    <ul class="tag-handler">
                    </ul>
                </section>
            </div>
        </div>

JS

<script type="text/javascript">
  $(".tag-handler").tagHandler({
      getData: { tagcategoryid: $(".tag-handler-category").data('category') },
      getURL: '/tag/interest',
      autocomplete: true,
      autoUpdate: true
  });

</script>

Upvotes: 1

Views: 939

Answers (2)

Jai
Jai

Reputation: 74738

i guess you should change to this:

getData: { tagcategoryid: $(this).siblings(".tag-handler-category").data('category') },

As class selectors in js/jquery returns a collection, so you need to have a context for each element in the collection with keyword this and as the target element is at same level and its is a sibling of selector so you can use .siblings() method to get the target element.


Update: you can use .each() method:

<script type="text/javascript">
  $(".tag-handler").each(function(i, v){
      $(this).tagHandler({
          getData: { tagcategoryid: $(v).data('category') },
          getURL: '/tag/interest',
          autocomplete: true,
          autoUpdate: true
      });
  });

</script>

Upvotes: 1

vijayP
vijayP

Reputation: 11502

I think you are trying to fetch category number associated with current section. In that case get data() as follows:

$(this).closest("section").find(".tag-handler-category").data('category')

Upvotes: 0

Related Questions