You seem to be just starting out with jQuery. Well, once you get over the first little bit of the learning curve, prepare to have your mind blown! One of the most powerful features of jQuery is the ability to select elements in your document using CSS selectors.
allinputs = $("input"); // Selects all input elements in your DOM
allrequiredinputs = $("input.required"); //Selects all input elements with a class of "required" in your DOM
allrequireds = $(".required"); //Selects all elements regardless of the tag name that have a class of "required"
There are other answers in this thread that answer your question perfectly well so I won't try and duplicate them here. However, I do have a suggestion which might work better for you. Instead of loading a different image into the DOM when the state of the form changes, why not use a sprite with "good", "no good" and "blank" states and simply update the class of your validation element when the input field changes. This way, all possible states of your validation element are pre-loaded so feedback is instant rather than after the second or so it takes to download the image.
To learn more about sprites, read these:
You could then do something like this:
//CSS
.validation {
display: block;
float: left;
width: 10px;
height: 10px;
}
.validation.blank {
background: none;
}
.validation.good {
background: url(mysprite.gif) 0px 0px;
}
.validation.nogood {
background: url(mysprite.gif) 0px 10px;
}
//HTML
<form id="myForm" ... >
<div id="contactform_namerow">
<label for="name">Name</label><input type="text" id="name" name="name" />
<div class="validation"></div>
</div>
</form>
//jQuery
$(function(){
$('#myform input, #myform textarea').bind('change',function(){
if($(this).val == ""){
$(this).siblings(".validation").addClass("nogood").removeClass("good");
} else {
$(this).siblings(".validation").addClass("good").removeClass("nogood");
}
});
});
You can further optimise this by putting class names denoting how each field should validate on each input element. That way you can write some code that would validate email addresses by setting something like <input type="text" id="myemail" name="email" class="email">
and selecting all elements like that in jQuery by going $('input.email')...
Also, I'm sure there is a toggleClass function somewhere but I was too lazy to look it up.
But... the great thing about jQuery is the HUGE number of plugins available. This one is my personal favourite: http://bassistance.de/jquery-plugins/jquery-plugin-validation/
Once you learn how to use the plugin properly, I'm sure you'll find that it will do everything you want to acheive here and more!
Hope this helps and good luck!
Iain