jQuery function to display an alert when submitting blank fields I am new to jquery and implemented following function in a js file in case of error-

function before_submit_check_if_has_blank_field() {
    $("[type=submit]").click(function(e) {
        var of_key_field = $('.key_field')
        var of_val_field = $('.val_field')
        var should_run = 1

        if (of_key_field.length === 1) {
            $('.key_field:not(:first)').filter(function() {
                if (this.value === "") {
                    alert('Please Fill In Or Remove The Blank Fields First')
                    e.preventDefault();
                    should_run = 0
                }
            });
        } else {
            $('.key_field').filter(function() {
                if (this.value === "") {
                    alert('Please Fill In Or Remove The Blank Fields First')
                    e.preventDefault();
                    should_run = 0
                }
            });
        }

        if (should_run != 0) {
            if (of_val_field.length === 1) {
                $('.val_field:not(:first)').filter(function() {
                    if (this.value === "") {
                        alert('Please Fill In Or Remove The Blank Fields First')
                        e.preventDefault();
                        should_run = 0
                    }
                });
            } else {
                $('.val_field').filter(function() {
                    if (this.value === "") {
                        alert('Please Fill In Or Remove The Blank Fields First')
                        e.preventDefault();
                        should_run = 0
                    }
                });
            }
        }

        update_config_field_from_key_value_field()
    });
}


The above code snippet is a part of my jquery where I am displaying a layout to the user with some fields and once those fields are empty then I am showing alert message while saving the form.

In above function I am repeating following lines of alert message which must be replaced by standard one-


if (this.value === "") {
    alert('Please Fill In Or Remove The Blank Fields First')
    e.preventDefault();
    should_run = 0
}



Can anyone please review my code and refactor it?
Your code can be refactor in multiple ways. To remove code repetition, create a new function for repeated code and use it as a callback of each filter.

function someFunc(e) {
  if (this.value === "") {
    alert('Please Fill In Or Remove The Blank Fields First')
    e.preventDefault();
    should_run = 0
  }
}


Use above function as

$('.key_field:not(:first)').filter(someFunc);


This will automatically remove redundant code as well as reduce number lines.

Suggestions:

Instead of playing around DOM and get value for each field separately, try to use serializeArray method of JQuery. See example

Please make habit to use ; to terminate line.

Hope this is helpful.