humbleiam humbleiam - 6 months ago 18
Ajax Question

Dynamic content data id not working in jquery

Have a dynamic html div

<a data-id="17" onclick="getcustomer();">
<div class="note note-success">
<h4 class="block">A</h4>
<p>Email : a@gmail.com</p>
<p>Mobile : 8</p>
<p>DOB : 0000-00-00</p>
</div>
</a>


On the above anchor's on click.it calls this function

function getcustomer(){
var id = $(this).data('id');
alert (id);
$.post(base_url+'who/customer', {
customer_id: id
}, function(data, status){
console.log(data);
});
}


But alert receiving is undefined.

How will I take
data-id
value?

This is dynamic field. This a's are added after dom load.

Answer

this does not refer to the element but to window

Pass this as argument for getcustomer function

function getcustomer(elem) {
  var id = $(elem).data('id');
  alert(id);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a data-id="17" onclick="getcustomer(this);">
  <div class="note note-success">
    <h4 class="block">A</h4>
    <p>Email : a@gmail.com</p>
    <p>Mobile : 8</p>
    <p>DOB : 0000-00-00</p>
  </div>
</a>

Or better use jQuery event binding using .on method

$('.eventBinding').on('click', function() {
  var id = $(this).data('id');
  alert(id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a data-id="17" class='eventBinding'>
  <div class="note note-success">
    <h4 class="block">A</h4>
    <p>Email : a@gmail.com</p>
    <p>Mobile : 8</p>
    <p>DOB : 0000-00-00</p>
  </div>
</a>