Highlight Form Focus with Prototype

Last updated: Jul 9, 2008

I recently made a purchase through Paypal (with my trusty paypal security key) and noticed that their forms really stood out. They had an effect on their forms that would highlight the row in which you are currently typing. I thought this was a very elegant use of ajax that really added value to the form. This is why I created my own version of it.

You can also go to Paypal and see their version of the effect.

The html

<html>
<head>
<link rel="stylesheet" type="text/css" href="screen.css" />
<script src="js/prototype.js" type="text/javascript"></script>
<script src="js/scriptaculous.js" type="text/javascript"></script>
</head>
<body>
<form action="" method="post">
<table>
<tr id="tr1"><td>Text Field 1: </td><td><input name="input 1" type="text"/></td></tr>
<tr id="tr2"><td>Text Field 2: </td><td><input name="input 2" type="text"/></td></tr>
<tr id="tr3"><td>Text Field 3: </td><td><input name="input 3" type="text"/></td></tr>
<tr id="tr4"><td>Text Field 4: </td><td><input name="input 4" type="text"/></td></tr>
<tr id="tr5"><td>Text Field 5: </td><td><input name="input 5" type="text"/></td></tr>
<tr id="tr6"><td>Text Field 6: </td><td><input name="input 6" type="text"/></td></tr>
<tr id="tr7"><td>Drop down: </td><td><select name="checkBox">
            <option>yes</option>
            <option>no</option>
        </select></td></tr>
<tr id="tr8"><td>Drop down 2: </td><td><select name="checkBox">
            <option>yes</option>
            <option>no</option>
        </select></td></tr>
<tr id="tr9"><td>Check Box: </td><td><input name="checkBox" type="checkbox" value="checkBox"/></td>

<tr><td></td><td><input type="submit" value="submit" /></td></tr>
</form>
</table>
</body>
</html>

The Ajax

Now we add the ajax above the form. This will add the css class, “highlight” to each table row. And also remove the class when called upon.

<script language='javascript'>
function highlightRow(theRow) {
    $(theRow).addClassName('highlight');
}
function unhighlightRow(theRow) {
    $(theRow).removeClassName('highlight');
}
</script>

onFocus and onBlur

Now all there is to do is add the onFocus and onBlur to the input tags in our form. Add this with the corresponding table row.

onFocus="highlightRow('tr1')" onBlur="unhighlightRow('tr1')"

Thats it…

Need to print shipping labels on your site?

Checkout my product RocketShipIt for simple easy-to-use developer tools for UPS™ FedEx™ USPS™ and more.

Get notified on new posts or other things I'm working on

Share: