Web Develop Wolf Web Develop Wolf - 2 years ago 130
jQuery Question

Unable to extract text from data attribute

I have Bootstrap Table that contains an edit button on each row. I've used a data formatter to make the pass the id of the record over with a data attribute that can be extracted when clicked. When I inspect the element in the console I can see the ID is in the dataset property, but when I try to get it out using element.dataset the console contains an error telling me that the dataset is undefined. It's frustrating because I can see it's there!

Here's my click event:

$(".job-edit").click(function(event) {
var editModal = $("#jobEditModal");
var clicked = $(event.target);
var id = clicked.dataset.jobid;
console.log(id);
event.stopPropagation();
//editModal.modal();
});


And the formatter that sets the button up:

job.editFormatter = function (value) {
return "<button class='btn job-edit text-center' data-jobId='" + value + "'><i class='fa fa-pencil-square-o' aria-hidden='true'></i> Edit</button>";
}


So far I've tried replacing
.dataset
with
.getAttribute()
, but that didn't work either, I've also tried changing the casing of
jobid
to
jobId
, past that I'm not sure what could be causing the problem.

Answer Source

Your issue is because clicked is a jQuery object which has no dataset property.

To fix this you need to use the native element reference:

var id = e.target.dataset.jobid;

Alternatively, use the data() method of the jQuery object:

var id = clicked.data('jobid');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download