Get value from clicked parent in jQuery

369
January 21, 2017, at 00:36 AM

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.

Answer 1

Try

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

Answer 2

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");

Answer 3

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>

Answer 4

try this, whitout the node 'a'

$('.container').on('click', '.switchStatus', function() {
    var module = $(this).data('module');
    alert(module);
});
READ ALSO
How can I make a function defined inside another function be in the window scope?

How can I make a function defined inside another function be in the window scope?

I am creating a wrapper for some arbitrary code (let's call it managed code)The managed code may include some functions that are defined in the window scope and are expected by other scripts on the page (horrible, 1997, practices, I know, but such is what I have to deal with),...

228
Get table width after ajax loaded content in it

Get table width after ajax loaded content in it

How do I get table width after AJAX has loaded content into it? For example, before content is loaded the width is 1160After content is loaded the width is 1260

302
Open a jQuery Mobile Collapsible Set

Open a jQuery Mobile Collapsible Set

In jQuery Mobile, I have a collapsible set:

315
Click next link after click first

Click next link after click first

I am trying to after click in the "State" and press "OK" I want to trigger the click in the next link ("a")

271