About   -   Contact   -   Purchase   -   Search   -   What's New

Javascript Multiple CSS Styles and Validation
The following example shows a nice CSS feature which I use for client side JavaScript validation routines. It relies on the feature of CSS which allows you to combine multiple CSS classes together. I have created a small contrived example below to show how it works, but the main idea is that you have a set of styles which you use for your input labels, then you have an error style which you merge onto any field labels when you want to show the field had an error.

In your validation routine you can concatenate the error style onto the elements classname, when the field is not in error you just check the classname for the special error style and remove it. This way you can have a variety of label styles and the JavaScript error highlighting will work generically.

.InputLabel { color:#000; padding-right:40px; }
.InputError { background-image: url( http://www.pbdr.com/images/cross.gif ); 
	background-repeat: no-repeat; background-position: 1px right; }
<script language="javascript">
function fShow( showError )
	var fieldLabel;
	fieldLabel = document.all['lbl_YourName'];
	if( showError )
		fieldLabel.className += " InputError";
		fieldLabel.className = 
			fieldLabel.className.replace( " InputError", "" );
			<td><label id="lbl_YourName" class="InputLabel" 
				for="YourName">Your Name</label></td>
			<td><input type="text" name="YourName"></td>
			<td><input type="button" 
				value="Show" onclick="fShow(true);"></td>
			<td><input type="button" 
				value="Hide" onclick="fShow(false);"></td>



Top of Page

Legal Notice

Ken Howe 2011