Simple jQuery Solution to Provide Default Values for Page Elements

Tony Pitale, Former Viget

Article Category: #Code

Posted on

When outputting sets of data that may or may not be present it is valuable to have some default to display in the cases when that data does not exist.  As this set grows to the point where detection becomes unwieldy, perhaps as new fields are added, having complex conditionals in your view code is typically not the best solution. In this example, Dining & Kitchen and Appliances have no information.

Listing Price Information
  • Original Price: $239,999.00
  • Low Price: $139,000.00
Dining & Kitchen
Appliances
Bedroom Information
  • Main Floor Beds: 2

Enter jQuery: with a simple statement we can easily detect which elements on our page are empty, and fill them with some default value to notify a user of that case.

$('ul').each(function() { if(jQuery.trim($(this).html()) == "") { $(this).html("<li>No information available</li>"); } }); 

The above code checks every unordered list element on the page to see if the html within is empty. If so, it adds a simple list item with a default value to inform the user that the section on the page has no information, instead of simply being empty. The end result is below.

Listing Price Information
  • Original Price: $239,999.00
  • Low Price: $139,000.00
Dining & Kitchen
  • No information available
Appliances
  • No information available
Bedroom Information
  • Main Floor Beds: 2

This solution has the benefit of speed, and a fairly accessible global reach, while keeping view code and helpers free of potentially gargantuan if statements.

Related Articles