JQuery get data attributes from element in table

Jeppe Christensen :

Suppose that i have a table that is populated with a razor @foreach loop.

For each row, I have a delete button, which looks something like this:

.....
<tr>
    <div style="cursor: pointer; display: inline-block; margin-left:5px" id="deleteEntity" data-Id="@Student.Id" data-Name="@Student.Name" data-Age="@Student.Age">                
        <i class="far fa-trash-alt"></i>
        <span style="color:#bfbfbf">Delete</span>
    </div>
</tr>

I want to have a jQuery function, that is capable of fetching the data attributes from my #deleteEntity div. Therefore I have done something along the lines of this:

$('#deleteEntity').on("click", function (event) {

    var button = $(event.target);
    var Id = button.data('Id')
    var Name = button.data('Name')
    var Age = button.data('Age')
    debugger;
});

However based on what I have done above, all of my values are Undefined.

  • Therefore, how do I correct this, so that I get the values that are specific to this delete button in my table?
David :

You should be able to get the button from $(this) inside the handler. However, you're re-using the same id on every button so the behavior of the click handler is essentially undefined. You'll want to use a class instead.

Additionally, the name for a data-* attribute must not contain capital letters. So simply make them lowercase.

For example:

$('.deleteEntity').on("click", function (event) {
    var button = $(this);
    var id = button.data('id');
    var name = button.data('name');
    var age = button.data('age');
    console.log(id);
    console.log(name);
    console.log(age);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="cursor: pointer; display: inline-block; margin-left:5px" class="deleteEntity" data-id="@Student.Id" data-name="@Student.Name" data-age="@Student.Age">                
    <i class="far fa-trash-alt"></i>
    <span style="color:#bfbfbf">Delete</span>
</div>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=32942&siteId=1