javascriptjquery

jQuery .trigger("change") not working


I can't get .trigger("change") to work. Anyone know why?

jQuery(document).ready(function () {

    jQuery("select[id='DROPDOWNID']").change(function () {

        var selectedIndex = jQuery("select[id='DROPDOWNID']").prop('selectedIndex');

        switch (selectedIndex) {
            case 0:
                hideVarforProspekt();
                break;
            case 1:
                hideOrdervarde();
                break;
            case 2:

                break;
            case 3:
                hideSektor();
                break;
        }
    });

    ** jQuery("select[id='DROPDOWNID']").trigger("change"); **


    function hideVarforProspekt() {
        jQuery("input[id='IDFROMSHAREPOINT']").closest('tr').hide();
    }

    function hideSektor() {
        jQuery("table[id='IDFROMSHAREPOINT']").closest('tr').hide();
    }

    function hideUppskOrder() {
        jQuery("input[id='IDFROMSHAREPOINT']").closest('tr').hide();
    }
});

Solution

  • Sometimes the usage of trigger is not necessary:

    // use just jQuery("#DROPDOWNID") instead
    var select = jQuery("select[id='DROPDOWNID']");
    
    // placing the handler in separate function
    var changeHandler = function () {
        var selectedIndex = select.prop('selectedIndex');
        switch(selectedIndex) {
            case 0:
                hideVarforProspekt();
            break;
            case 1:
                hideOrdervarde();
            break;
            case 2:
    
            break;
            case 3:
                hideSektor();
            break;
        }
    }
    
    // cache your jQuery selectors. It's a good practice
    // and improves the readability
    select.change(changeHandler);
    
    // triggering
    changeHandler();