Charles Smith
Charles Smith

Reputation: 3289

Undefined value of $(this).data(value) with jQuery click() method

Im my Rails 5 app, I am building a dynamic menu to route users to a particular part of the site based on their location. When they click on a menu item from the home page a modal is show for them to choose one of four locations we deliver to. A function with the click method then should grab the data- attribute and insert it into the url path to redirect them. I cannot seem to get the data attribute to pass through even if hard coded - I just get an undefined in the console.

I am not including the modal code here because it is not the issue; it opens and inserts /undefined/undefined/ in the path just like the console. My issue is only in getting this data value.

_sidebar.html.erb

<div id="ss_menu">
  <% @cat.each do |c| %>
    <div class="ss_button"><%= c.name %></div>
    <div class="ss_content">
      <ul>
        <% c.subcategories.each do |s| %>
          <li>
            <a href="#" 
               data-id="<%= s.id %>" 
               data-category="<%= c.slug %>" 
               data-subcategory="<%= s.slug %>" 
               data-toggle="modal" 
               data-target=".mlc-modal"><%= s.name %></a>
          </li>
        <% end %>
      </ul>
    </div>
  <% end %>
</div>

script

<script type="text/javascript" charset="utf-8">
    $(document).on("click", ".ss_button", function () {
        var id = $(this).data('id');
        var category = $(id).data('category');
        var subcategory = $(id).data('subcategory');
        console.log(id);
        console.log(category);
        console.log(subcategory);
        $('.modal-content a').attr('href', function () {
            return this.href + category + '/' + subcategory;
        });
    });
</script>

Upvotes: 1

Views: 909

Answers (2)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72269

var id = $(this).data('id');

Here $(this) refers to <div class="ss_button"> which have no data-id attribute.

So it will always comes(outputs) as undefined.

Upvotes: 0

frogatto
frogatto

Reputation: 29287

ss_button element on itself doesn't have any data properties. So, this in that function which refers to <div class="ss_button">, points to an element that doesn't have any data properties. That's why $(this).data('id') returns undefined.

Upvotes: 1

Related Questions