0

I have code as follows:

<div id="make" data-make-unique-id="{{ values.unique_id }}">
     <div class="d-flex flew-row align-items-center">
          <i class="icon-{{ key|lower }}" style="font-size: 19px;"></i>
          <div class="text-capitalize">{{ key|lower }}</div>
     </div>
     <div class="d-flex align-items-center">{{ values.counter }}</div>
</div>

I want to capture click event on the div with id make. And I want to get data-make-unique-id tag value, no matter if is clicked on the div with id make or on some of the children.

I tried something as follows:

$(document).on('click', '#make', (e) => {                
    const unique_id = $(this).data("make-unique-id");
    debugger;
});

But if it doesn't work.

Boky
  • 11,554
  • 28
  • 93
  • 163
  • You have been provided with two working answers if they don't work I suspect that your CSS is interfering, do you have any console errors? – M T Nov 15 '19 at 09:17
  • 1
    `$(document).on('click', '#make', (e) => { const unique_id = $(e.target).data("make-unique-id"); debugger; });` but if #make is not dynamic, just use `$("#make").on("click",function() { const unique_id = $(this).data("make-unique-id"); });` - note the difference between (e) => and function() – mplungjan Nov 15 '19 at 09:17
  • `this` context is different in the provided scope.. If not, are you looking for jQuery [attribute=value] Selector? – Jry9972 Nov 15 '19 at 09:18

2 Answers2

1

This should work for you :-

$("#make").on("click", function(event){
  var unique_id = $(this).data("make-unique-id");
});
M T
  • 136
  • 1
  • 8
  • 7
    I think it's worth pointing out that it's all about `function` versus `() => {}`. The latter does not create new context and therefore `$(this)` is not what OP expect – Sebastian Kaczmarek Nov 15 '19 at 09:09
  • Yes agree'd not sure why the two valid answers to this question are being down voted though. – M T Nov 15 '19 at 09:12
1

Add the click listener on the element with id 'make'. And also if you want to bind this then use normal function instead of arrow function.

See below the sample code.

  $(document).ready(function() {
    $('#make').click(function() {
        const unique_id = $(this).data("make-unique-id");
        console.log(unique_id);
    });
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="make" data-make-unique-id="2">
        <div class="d-flex flew-row align-items-center">
            <i class="icon-{{ key|lower }}" style="font-size: 19px;"></i>
            <div class="text-capitalize">{{ key|lower }}</div>
        </div>
        <div class="d-flex align-items-center">{{ values.counter }}</div>
    </div>

Hope this will solve the issue.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Sohail Ashraf
  • 10,078
  • 2
  • 26
  • 42