0

The Scenario:

I would like to fire the function checkDOMChange (which hides ul tags that are empty) once an input is filled and unfocussed but currently, the function is not being called. Here is a fiddle.

function checkDOMChange() {
  if ($("div[id$='DoIQualify_financials'] div").hasClass("field-invalid")) {
    if ($('.borrower1Salary_errors li').length == 0) {
      jQuery("ul.borrower1Salary_errors").hide();
    }
    if ($('.borrower2Salary_errors li').length == 0){
      jQuery("ul.borrower2Salary_errors").hide();
    }
  }
DylanB
  • 431
  • 3
  • 16
Nooblike
  • 150
  • 1
  • 10

2 Answers2

0

You need to change your script to be defined when the script is being parsed, at runtime there is no field-invalid class because the DOM is empty (no HTML elements have been loaded yet).

To do this, assign the function to a variable, shown below.

checkDOMChange = function (){
       if ($("div[id$='DoIQualify_financials'] div").hasClass("field-invalid")) {
           if ($('.borrower1Salary_errors li').length == 0) {
               jQuery("ul.borrower1Salary_errors").hide();
           }
           if ($('.borrower2Salary_errors li').length == 0) {
               jQuery("ul.borrower2Salary_errors").hide();
           }
       }
   } 

This way, the function is invoked after the DOM has loaded the required elements. There's a great explanation here which explains the difference in more detail.

You could also choose to put your function in a window.onload event which waits until the DOM has loaded before executing scripts.

A third option would be to put your script just before the closing body tag of your HTML (browsers read HTML top-down so it will load the DOM before reading the script tag).

You also need to close your first if statement

Community
  • 1
  • 1
DylanB
  • 431
  • 3
  • 16
0
   function checkDOMChange() {
       if ($("div[id$='DoIQualify_financials'] div").hasClass("field-invalid")) {
           if ($('.borrower1Salary_errors li').length == 0) {
               jQuery("ul.borrower1Salary_errors").hide();
           }
           if ($('.borrower2Salary_errors li').length == 0) {
               jQuery("ul.borrower2Salary_errors").hide();
           }
       }
   }
   $(document).ready(function () {
       $(document).on('blur', '.inputbox', checkDOMChange);
   }

This is what you want, I Guess

Shiva
  • 11,485
  • 2
  • 67
  • 84