lundi 10 juillet 2017

Refactor Conditional Statement in Jquery

I am new to js and jquery but tried my best to write this code the best way possible. My question is what is the best way to refactor this as it is very ugly but functional any help would be great:

function togglePrintersOptionBlock(selectBlock) {
    var selectedVal = $(selectBlock).children('option:selected').val();
        if (selectedVal && selectedVal.match(/DPD/i)) {
            $(dhlPrinters).hide().find('select');
            $(dpdPrinters).show().find('select');
            $(dpdPrinters).on('change', 'select', function() {
                if ($(this).val()) {
                    $(printPackagingSlipBtn).show();
                } else {
                    $(printPackagingSlipBtn).hide();
                }
            });
        } else if(selectedVal && selectedVal.match(/DHL/i)) {
            $(dpdPrinters).hide().find('select');
            $(dhlPrinters).show().find('select');
            $(dhlPrinters).on('change', 'select', function() {
                if ($(this).val()) {
                    $(printPackagingSlipBtn).show();
                } else {
                    $(printPackagingSlipBtn).hide();
                }
            });
        } else {
            $(allPrinters).hide().find('select');
            if (selectedVal) {
                $(printPackagingSlipBtn).show();
            } else {
                $(printPackagingSlipBtn).hide();
            }
        }
    }

    $(shippingOptions).change(function(){
        togglePrintersOptionBlock(this);
    });

    togglePrintersOptionBlock(shippingOptions);
};

Aucun commentaire:

Enregistrer un commentaire