Saturday, November 10, 2012

Oracle Apex - Dynamically Color Text field

It is often useful to highlight certain fields when certain (usually incorrect) values are entered as a form of on the fly validation. 

Suppose you had a fairly large form with many fields many of which only accept numbers. It would be much more user friendly if you could alert end-users to incorrect values as they enter it, rather than let them submit and have a big list of invalid entries to sift through.



1) Put the following code in page header.

<script language="JavaScript" type="text/javascript">

function setCol(pThis)
{
var vv = $v(pThis);
var cls = '#'+pThis;
if(isNaN(vv))
{
$(cls).css("background-color","red");
}
else
{
$(cls).css("background-color","white");
}
}


</script>

2) Create Dynamic Action with following configuration:
  1. Type Advanced (for pre-4.2)
  2. Event: change
  3. Selection Type: item
  4. Item(s): P1_ENAME, P1_MOB (comma seperate the list of items)
  5. True Action: 
    1. Action: Execute Javascript Code
    2. Code: setCol(this.triggeringElement.id);
  6. Affected Items:
    1. Pick the items in #4 above.

What this does is basically highlight textfield when non-numeric characters are entered (isNAN). 

Here is how it should look like if implemented properly. You can take this and do more fancy stuff like validating against regex. 

http://apex.oracle.com/pls/apex/f?p=21796:1