//Search for all mandatory fields, point out that they are not filled in
function validate( formID , className )
{
var form = document.getElementById( formID ),
elements = form.getElementsByClassName( className ),
i;
//It is possible that there are no mandatory fields
if( !elements || !elements.length )
return
//We are counting on smart developers, who only apply the mandatory class
//to text boxes.
for( i = 0 ; i < elements.length; i++ )
{
var element = elements[i];
if( !element.value )
{
nagUser( element )
//informUser( element );
element.focus();
return;
}
}
}
/* Tell the user what to do */
function nagUser( element )
{
var nagElement = document.getElementById( "nag" );
nagElement.textContent = "Please fill in the " + findLabel( element );
}
/* Dont tell the user to fill in a field if (s)he did */
function stopNagging()
{
var nagElement = document.getElementById( "nag" );
nagElement.textContent = "";
}
/* Old Skool alert, can be annoying to the user */
function informUser( element )
{
alert( "Please fill in the " + findLabel( element ) );
}
/* Find a matching label for a given input box, return "field" if nothing is found */
function findLabel( element )
{
while( element && element.localName != "label" )
element = element.previousSibling;
return element.textContent || "field";
}
/* This makes the nagging stop when the user exits an inputbox that is filled in */
var inputBoxes = document.getElementsByTagName( "input" );
for( var i = 0 ; i < inputBoxes.length ; i++ )
{
var inputBox = inputBoxes[i];
inputBox.addEventListener( "blur" , function(e)
{
if( this.value )
stopNagging();
});
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.