burnt1ce
burnt1ce

Reputation: 14917

jQuery: $(this).data() is null

I don't know why $(this).data() returns null in button click event handler but when debugging in firebug, $("#" + $(this).attr("id")).data() returns the data that i expect.

for (var i = 0; i < options.AvailableOperations.length; i++) {
        var operation = options.AvailableOperations[i];
        var button = $(this).find("#btn" + operation);
        button.data("operation", operation);
        button.data("entityId", options.entityId);
        button.parent().removeClass('disabledRevButton');

        var data = { operation: operation, entityId: options.entityId };
        button.click(function () {

            $.postJson({
                url: GlobalVars.perfomDFOperation,
                data: $(this).data(),
                success: function (data) {
                    if (data != null) {
                        if (data.IsSuccess && data.RefreshPage) {
                            location.reload(true);
                        }
                        else if (!data.isSuccess) {
                            alert("error: " + data.Message)
                        }
                    }
                }
            });
        });
    }

Upvotes: 2

Views: 5044

Answers (2)

SirCommy
SirCommy

Reputation: 270

Isn't the variable 'button' the seletion you're looking to fetch data() from? Use buton.data() because $(this) can easily reference something else along the process.

I'd recommend you to use console.log() for debugging purposes, for example, before you attempt to post the JSON, do a console.log($(this)) and see what it references.

Upvotes: 0

Richard Neil Ilagan
Richard Neil Ilagan

Reputation: 14737

The this may not be referring to the button itself anymore since it's inside the $.postJson() scope already.

You may want to try using a closure.

button.click(function(){

    var myBtn = $(this);
    $.postJson({
        data: myBtn.data(),
        // blah
    });

});

I'm not sure, but worth a try.

Upvotes: 1

Related Questions