Tuesday, 24 September 2013

Highlight Empty Fields

A question that came up this week was how to highlight to a user that fields in a form don't have a value, but without stopping the form submission or annoying them with popups/confirmation dialogs. Essentially flagging up 'nice to have' fields that are empty, but leaving the required fields with the standard Salesforce decoration and the fields that nobody really cares about alone.

When the form is initially rendered, this is easy enough to achieve through conditional styling, but the problem with this is that it can't change the background when the user populates the field - instead, a form postback is required and even if rerendering is used to minimise the page updates, a full round trip every time a field is changed is a pretty hefty tax on the user.

This seemed like a good fit for jQuery, so I fired up the Force.com IDE and created a simple lead entry page that highlights a selection of empty fields:

Screen Shot 2013 09 24 at 19 26 14

In order to easily identify the nice to have fields, I gave them each an id that started with 'flagEmpty':

<apex:inputField id="flagEmptyFName" value="{!Lead.FirstName}" />
<apex:inputField id="flagEmptyEmail" value="{!Lead.Email}" />

Next, I wrote the function to apply the necessary style class.  This takes all or part of an id, finds any elements containing the id and for each match, checks if the field has value.  If it does, the 'fieldpopulated' class is applied, otherwise the 'fieldempty' class is applied.  When the appropriate class is applied, the other class is removed:

function flagEmpty(theId)
{
  $("[id*='" + theId + "']").each(function(index, ele) {
		if($(ele).val().length > 0)
		{
			$(ele).removeClass('fieldempty');
			$(ele).addClass('fieldpopulated');
		}
		else
		{
			$(ele).removeClass('fieldpopulated');
			$(ele).addClass('fieldempty');
		}
	});
}

 When the page is initially loaded, the id fragment 'flagEmpty' is passed to the function, which finds all of the elements I've marked in this fashion and highlights the background:

flagEmpty('flagEmpty');

Finally, an onchange handler is added to each element with an id containing 'flagEmpty'. This handler extracts the id of the element and executes the 'flagEmpty()' method, passing the id as the parameter:

$("[id*='flagEmpty']").change( function(event) {
	flagEmpty($(event.target).attr('id'));
});

The fields marked as 'flagEmpty' are originally rendered with a yellow background:

Screen Shot 2013 09 24 at 19 29 22

but after filling in a field and moving focus, the onchange handler fires and changes the background to white:

Screen Shot 2013 09 24 at 19 31 26

The Visualforce page is available at this gist

 

No comments:

Post a Comment