View Single Post
  #29 (permalink)  
Old 02-21-2008, 01:23 AM
prasannavigneshr prasannavigneshr is offline
D-Web Incredible
 
Join Date: Feb 2007
Posts: 1,321
prasannavigneshr is on a distinguished road
Send a message via MSN to prasannavigneshr
Thumbs up ColdFusion Tips & Tricks - Javascript: Checking to see if dropdown selection boxes h

javascript: Checking to see if dropdown selection boxes have a selection


This function comes in handy if you have multiple required selection boxes and you want to easily check to see if the user has selected a value.

Example HTML/CFML code:
Code:
<script language="Javascript">

// Pass in a list of drop down fields that must have an item selected other than the first one (selectedIndex > 0)
// Example: if (!ValidateDropDown(document.ServiceForm,'ChannelCodeDesc|UserLevel','Channel Code|User Level')) return false;
function ValidateDropDown(thisform,Fields,Desc)
{
	var tmpVal='';
	var FieldArray=new Array();
	var DescArray=new Array();
	var tmp=0;
	var idx=0;
	// Create array for Field list
	tmpVal=Fields;
	do
	{
		tmp=tmpVal.indexOf('|');
		if (tmp == -1)
		{
			if (tmpVal != '')
			{
				FieldArray[FieldArray.length]=tmpVal;
				tmpVal='';
			}
		} else {
			FieldArray[FieldArray.length]=tmpVal.substring(0,tmp);
			tmpVal=tmpVal.substring(tmp + 1);
		}
	}
	while (tmpVal != '');
	// Create array for Desc list
	tmpVal=Desc;
	do
	{
		tmp=tmpVal.indexOf('|');
		if (tmp == -1)
		{
			if (tmpVal != '')
			{
				DescArray[DescArray.length]=tmpVal;
				tmpVal='';
			}
		} else {
			DescArray[DescArray.length]=tmpVal.substring(0,tmp);
			tmpVal=tmpVal.substring(tmp + 1);
		}
	}
	while (tmpVal != '');
	// Check to see if passed strings are of equal length
	if (FieldArray.length != DescArray.length)
	{
		alert('Fatal error: ValidateDropDown - Passed lists do not have the same length');
		return false;
	}
	// Validate fields
	for (i=0; i<FieldArray.length;i++)
	{
		eval('idx=thisform.' + FieldArray[i] + '.selectedIndex');
		if (idx == 0)
		{
			alert('Please select an item for ' + DescArray[i] + '.');
			return false;
		}
	}
	return true;
}

function SubmitForm()
{
	if (!ValidateDropDown(document.Test,'Gender|Age','Gender|Age Range')) return false;

	alert('All is okay!');
}
</script>

<form name="Test">
Gender:
<select name="Gender" size="1">
	<option value="">&lt; Select &gt;</option>
	<option value="M">Male</option>
	<option value="F">Female</option>
</select>
<br>
Age Range:
<select name="Age" size="1">
	<option value="">&lt;  Select &gt;</option>
	<option value="1">1-10</option>
	<option value="2">11-20</option>
	<option value="2">21-30</option>
	<option value="2">31-99</option>
</select>
<br><br>
<input type="Button" value="Go!" onClick="SubmitForm()">
</form>
__________________
Prasanna Vignesh
MCPD | Web Developer
Reply With Quote