Enabling or disabling buttons on certain events I need to run the following checks in two occasions:


When a certain modal is first shown or clicked,
When one of two inputs is filled.


How can I remove redundancy in the following code?

jQuery(document).ready( function($) {
    $(document.body).on( 'DOMNodeInserted click',  '.media-modal', function( event ) {
        var test = $('label.setting[data-setting=alt] input:visible').val();
        var test2 = $('input[data-setting=alt]:visible').val();
        if (!test &amp;&amp; !test2) {
            $('.media-modal .media-button-insert').prop("disabled",true);
            $('.media-modal .media-button-select').prop("disabled",true);
        } else {
            $('.media-modal .media-button-insert').prop("disabled",false);
            $('.media-modal .media-button-select').prop("disabled",false);
        }
        $(document.body).on( 'input propertychange paste',  'label.setting[data-setting=alt] input, input[data-setting=alt]', function( event ) {
            var test = $('label.setting[data-setting=alt] input:visible').val();
            var test2 = $('input[data-setting=alt]:visible').val();
            if (!test &amp;&amp; !test2) {
                $('.media-modal .media-button-insert').prop("disabled",true);
                $('.media-modal .media-button-select').prop("disabled",true);
            } else {
                $('.media-modal .media-button-insert').prop("disabled",false);
                $('.media-modal .media-button-select').prop("disabled",false);
            }
        });
    });
});
I would write it as something like:

jQuery(document).ready( function($) {

    function updateDisabled() {
        var test     = $('label.setting[data-setting=alt] input:visible').val();
        var test2    = $('input[data-setting=alt]:visible').val();
        var disabled = !test &amp;&amp; !test2;
        $('.media-modal .media-button-insert').prop("disabled", disabled);
        $('.media-modal .media-button-select').prop("disabled", disabled);
    }   

    $(document.body).on( 'DOMNodeInserted click', '.media-modal', updateDisabled);
    $(document.body).on( 'input propertychange paste', 'label.setting[data-setting=alt] input, input[data-setting=alt]', updateDisabled);

}


You could also rewrite:

$('.media-modal .media-button-insert').prop("disabled", disabled);
$('.media-modal .media-button-select').prop("disabled", disabled);


As 

$('.media-modal .media-button-insert, .media-modal .media-button-select').prop("disabled", disabled);


(Although I prefer keeping them separate) or maybe better giving your buttons an extra class and writing:

$('.media-modal .media-button').prop("disabled", disabled);