Breakdown of script:
1. When the page is rendered a JavaScript hook is added to the first <input>, on the onblur trigger. It calls the function setFieldClassName.
2. Inside that function, it checks the length of field1 for being greater than zero. If so, field2 is assigned the CSS class className. If not, it is assigned a blank class (so that if the user deletes what they originally entered, the class will be wiped.)
Code follows.
HTML Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Adding a class to a field once another field is completed</title>
<style type="text/css">
.className
{
color: red;
}
</style>
</head>
<body>
<form id="testform" action="#">
<p>Field 1: <input type="text" name="field1" id="field1" class="className" /></p>
<p>Field 2: <input type="text" name="field2" id="field2" /></p>
<p><input type="submit" name="submit" value="Submit testForm" /></p>
</form>
</body>
<script type="text/javascript">
setFieldClassName = function()
{
var fieldToValidate = document.getElementById('field1');
var fieldToChangeClass = document.getElementById('field2');
if(fieldToValidate.value.length > 0)
{
fieldToChangeClass.className = 'className';
}
else
{
fieldToChangeClass.className = '';
}
}
var inputElements = document.getElementsByTagName('input');
inputElements[0].onblur = setFieldClassName;
</script>
</html>
|