Dexa
Dexa

Reputation: 99

Don't know why can't get data-id with jquery. It's always undefined

Trying to get data-id with jquery. But with no success. My jsp with data-id:

<button class="btn btn-danger" id="delete-track" data-id="${track.id}"><i class="fa fa-trash-o"></i> Delete</button>

And my js:

var TracksController = function(){

};

TracksController.prototype.deleteTrack = function (el) {

    var id = $(el).attr("data-id");

    $.ajax({
        url: '/tracks/delete',
        type: 'post',
        data: {
            id: id
        },
        success: function (data){



        }
    })

};

TracksController.prototype.init = function () {

    var that = this;

    $('#delete-track').on('click', function () {
        that.deleteTrack();
        return false;
    });

};

$(function(){
    var tracksController = new TracksController();
    tracksController.init();
});

Thought that it had to work but... Can someone tell me what am I doing wrong?

Upvotes: 1

Views: 549

Answers (2)

dannyjolie
dannyjolie

Reputation: 11339

You are calling that.deleteTrack() without any arguments, but deleteTrack expects an element.

var id = $(el).attr("data-id"); fails because el is undefined

A fiddle for demo purposes: https://jsfiddle.net/kjb6ug9c/2/

Upvotes: 1

Blue
Blue

Reputation: 22911

Try $(el).data("id"). The data function allows you to store/fetch the data stored in elements. You can read more about it here.

Upvotes: 2

Related Questions