V4n1ll4
V4n1ll4

Reputation: 6099

trigger my own jQuery function

I'm trying to trigger my own jQuery function using the following but it's not working. It doesn't even show the alert. Any ideas?

(function($){
    $.fn.loadWorksheets = function() {
    alert("test 123");
        var weekEnding = this.value;
        $.post("fetchRows.php", {week_ending: weekEnding}, function(data)
        {
            var data = $.parseJSON(data);
            $("#completedWorksheets > tbody").html("");

            if(data[0] !== false) {
                $(data).each(function(i,val){
                        var newRow = '<tr><td data-th="Week ending">' + data[i]["week_ending"] + '</td><td data-th="Employee">' + data[i]["employee"] + '</td><td data-th="Project">' + data[i]["project"] + '</td><td class="actions"></td></tr>';
                        $("#completedWorksheets tbody").append(newRow);
                });
            }
            else {
                $("#completedWorksheets tbody").append('<tr><td colspan="4">There are no worksheets for the selected week.</td></tr>');
            }
        });
    }
});

$('#week_ending_cm').on('change', function() {
    $.fn.loadWorksheets();
});

Thanks.

Upvotes: 1

Views: 92

Answers (3)

Erick Cortorreal
Erick Cortorreal

Reputation: 389

Your Js should be like this: (You were missing the two parenthesis at the end of your function definition block).

(function($){
$.fn.loadWorksheets = function() {
alert("test 123");
    var weekEnding = this.value;
    $.post("fetchRows.php", {week_ending: weekEnding}, function(data)
    {
        var data = $.parseJSON(data);
        $("#completedWorksheets > tbody").html("");

        if(data[0] !== false) {
            $(data).each(function(i,val){
                    var newRow = '<tr><td data-th="Week ending">' + data[i]["week_ending"] + '</td><td data-th="Employee">' + data[i]["employee"] + '</td><td data-th="Project">' + data[i]["project"] + '</td><td class="actions"></td></tr>';
                    $("#completedWorksheets tbody").append(newRow);
            });
        }
        else {
            $("#completedWorksheets tbody").append('<tr><td colspan="4">There are no worksheets for the selected week.</td></tr>');
        }
    });
}
})($); // <<<==== HERE WE INSTANTLY CALL IT

$('#week_ending_cm').on('change', function() {
    $.fn.loadWorksheets();
});

Upvotes: 2

Pointy
Pointy

Reputation: 413720

Your initial anonymous function is not being called. Its last line should look like

})(jQuery);

not just

});

Because the function is not called, the alert isn't shown and your jQuery plugin isn't defined.

As noted in a comment to your question, if you're making a function that isn't intended to be a jQuery method operating on a jQuery object, generally those are added as properties of $ and not $.fn.

Upvotes: 7

Pavel Komiagin
Pavel Komiagin

Reputation: 748

Try to replace last string of your function to this: })($);

Upvotes: 6

Related Questions