May 2010

Email this to a friend

In 1999 there was this IE4 or 5 browser I was grappling with, and I managed to cobble together a nasty 'imgSwap' kind of javascript to do these (at the time) fancy menu image swaps for a mouseover.

It was awesome.

Now, of course, we use CSS to do all of that.

But... I recently needed to do a form checker and decided that instead of just relying on a server-side data integrity check, which we still do, it was more user friendly to help users immediately identify their form completion issues. 

Plus, along came the need to do it faster, which means, giving the DOM elements ID's and testing these elements using a javascript.

Of course it also needed to be really reusable, because not all forms are alike, in fact, none are...

My solution is so easy to implement and therefore time saving, I thought it might be the kind of thing people wished they had in 1999. I sure did, but I have it now so better late than never.

Enjoy  

ps. Don't forget to just download the working example file at the bottom of this post.  

 

The Javascript

<script language="javascript">
var erroronform = "Your own personal message";

function checkFields(element) {
if (document.getElementById(element).value=="") {
document.getElementById(element).style.backgroundColor = "#fff564";
document.getElementById(element).style.border = "1px #8C0444 solid";
return false;
}
else {
document.getElementById(element).style.backgroundColor = "";
document.getElementById(element).style.border = "";
return true;
}
}

/*add your fields to verify in the 'list' var - remember to add the id="" to your html input*/

function verifyForm(form) {
var list = ["firstname","surname"];
var success = true;
for (var i = 0; i < list.length; i ++) {
if (!checkFields(list[i])) success = false;
}
if(success==false) {
alert(erroronform);
}
return success;
}

</script>

Download a working HTML example - zipped for convenience, MIT license

 


All logos, images and content copyright © 2010 - Webhaven International ApS - CVR. 30589971