Animesh D
Animesh D

Reputation: 5002

Unable to trigger change event of a dropdown element in document ready

In $(document).ready(), I am setting a particular dropdown's first element to be selected. I also need to trigger the change function on the dropdown as if the option were manually selected. If the change is triggered, the showTestsByPanel function is called and shows appropriate data associated with the selected dropdown option.

I am doing the following, but it doesn't help trigger the change function:

$(document).ready(function () {
    $("#lbpanel option:first-child").attr('selected', 'selected');
    $('#lbpanel').trigger('change'); // <-- this is not triggering the change

    $('#lbpanel').change(function () {
        var $this = $(this);
        var parentId = $("#lbpanel").find("option:selected").val();
        $("#selectedTests tr").each(function () {
            showTestsByPanel(parentId, $(this));
        });
    });
});

I also tried $('#lbpanel').change() instead, but that did not work as well.

If it helps:

What am I doing wrong?

Upvotes: 0

Views: 1406

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388406

You need to trigger the change event after the trigger handlers are registered, when the event is triggered it will invoke only those handlers which are already registered.

$(document).ready(function () {
    $("#lbpanel option:first-child").attr('selected', 'selected');

    $('#lbpanel').change(function () {
        var $this = $(this);
        var parentId = $("#lbpanel").find("option:selected").val();
        $("#selectedTests tr").each(function () {
            showTestsByPanel(parentId, $(this));
        });
    }).trigger('change'); // need to trigger the event after the handler is added
});

Upvotes: 1

You are trying to trigger change event before handler creation. That's why no effect.

So call the change() after registering change event handler

$(document).ready(function () {
    $("#lbpanel option:first-child").attr('selected', true);
    $('#lbpanel').change(function () {
        var $this = $(this);
        var parentId = $("#lbpanel").find("option:selected").val();
        $("#selectedTests tr").each(function () {
            showTestsByPanel(parentId, $(this));
        });
    }).change(); //added change here
});

Upvotes: 1

Related Questions