F__M
F__M

Reputation: 1598

Get value from clicked parent in jQuery

I have this code:

<div class="container">
     <div class="switchStatus btn-group" data-module="xxx">
          <a class="btn btn-primary">Active</a>
          <a class="btn btn-primary">Inactive</a>
     </div>
</div>

How can I get the data-module content ?

Actually, my code looks like this but it doesn't work:

$('.container').on('click', '.switchStatus a', function() {
    var module = $(this).data('module');
});

Thanks.

Upvotes: 1

Views: 50

Answers (4)

Vanquished Wombat
Vanquished Wombat

Reputation: 9525

Use closest('.switchStatus').

jQuery sets the scope of the callback function to the element which is the subject of the callback

So I guess that means the elements in the on selector parameter (.switchStatus a in this case)

$('.container').on('click', '.switchStatus a', function(event) {
    var module = $(this).closest('.switchStatus').data('module');
    console.log('My name is ' + module)
    event.stopPropagation() // always good to stop event bubbles after you have used them.
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
     <div class="switchStatus btn-group" data-module="Spartacus">
          <a class="btn btn-primary">Active</a>
          <a class="btn btn-primary">Inactive</a>
     </div>
</div>

Upvotes: 1

fingerprints
fingerprints

Reputation: 2960

try this, whitout the node 'a'

$('.container').on('click', '.switchStatus', function() {
    var module = $(this).data('module');
    alert(module);
});

Upvotes: 0

mhodges
mhodges

Reputation: 11116

Inside your click handler callback function, the this context will be bound to the <a> element that was clicked. To get the parent, you can use the .closest() method with a selector. It could look like the following:

$(this).closest("[data-module]").attr("data-module");

Upvotes: 1

VHS
VHS

Reputation: 10174

Try

var module = $(this).parent().data('module');

Upvotes: 2

Related Questions