jQuery function won't work with in single function but when split - any idea why! would highly be appreciated

Viewed 20
    $emailValidate.on('blur', function() {
        if (!$(this).val().match($emailRegx)) {
            $(this).closest('.emailed_field').find('.tooltips7 span').addClass('mod_span');
        } else if ($(this).val().match($emailRegx)) {
            $(this).closest('.emailed_field').find('.tooltips7 span').removeClass('mod_span');
        }

        else if ($(this).val().trim() =='') {
            $(this).closest('.emailed_field').find('.tooltips7 span').removeClass('mod_span');
            $(this).closest('.emailed_field').find('.tooltips8 span').addClass('mod_span');
        }
});

The code above doesn't work all in one function but, the Code Below works - don't know the magic - this is just a duplicate function

    $emailValidate.on('blur', function() {
        if (!$(this).val().match($emailRegx)) {
            $(this).closest('.emailed_field').find('.tooltips7 span').addClass('mod_span');
        } else if ($(this).val().match($emailRegx)) {
            $(this).closest('.emailed_field').find('.tooltips7 span').removeClass('mod_span');
        }
      });

      $emailValidate.on('blur', function(){
        if ($(this).val().trim() =='') {
            $(this).closest('.emailed_field').find('.tooltips7 span').removeClass('mod_span');
            $(this).closest('.emailed_field').find('.tooltips8 span').addClass('mod_span');
        }

    });
1 Answers

There are two semi-separate pieces of logic to carry out:

  • Check if the emailRegx matches and do something that branches as a result
  • Check if the input is empty and do something as a result

Change the else if at the bottom to an if, because it's separate.

$emailValidate.on('blur', function () {
    if (!$(this).val().match($emailRegx)) {
        $(this).closest('.emailed_field').find('.tooltips7 span').addClass('mod_span');
    } else if ($(this).val().match($emailRegx)) {
        $(this).closest('.emailed_field').find('.tooltips7 span').removeClass('mod_span');
    }

    if ($(this).val().trim() == '') {
        $(this).closest('.emailed_field').find('.tooltips7 span').removeClass('mod_span');
        $(this).closest('.emailed_field').find('.tooltips8 span').addClass('mod_span');
    }
});

Or, more concisely with toggleClass and saving the element in a variable:

$emailValidate.on('blur', function () {
    const emailedField = $(this).closest('.emailed_field');
    emailedField.find('.tooltips7 span').toggleClass(
        'mod_span',
        !$(this).val().match($emailRegx)
    );

    if ($(this).val().trim() == '') {
        emailedField.find('.tooltips7 span').removeClass('mod_span');
        emailedField.find('.tooltips8 span').addClass('mod_span');
    }
});
Related