IT Community - Software Programming, Web Development and Technical Support

ColdFusion Tips & Tricks

This is a discussion on ColdFusion Tips & Tricks within the ColdFusion Programming forums, part of the Web Development category; Forcing a user to relog after x number of minutes If you wish for a user to be redirected to ...


Go Back   IT Community - Software Programming, Web Development and Technical Support > Web Development > ColdFusion Programming

Register FAQ Members List Calendar Mark Forums Read

Reply
 
LinkBack Thread Tools Display Modes
  #21 (permalink)  
Old 02-18-2008, 09:09 PM
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 - Forcing a user to relog after x number of minutes

Forcing a user to relog after x number of minutes




If you wish for a user to be redirected to the login page after they have been inactive for x number of minutes instead of waiting for them to jump to another page, add the following line inside the <head></head> block of your html:

<META HTTP-EQUIV="refresh" CONTENT="901;URL='login.cfm'">

This assumes that your session timeout is set for 15 minutes (900 seconds).
__________________
Prasanna Vignesh
MCPD | Web Developer
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Sponsored Links
  #22 (permalink)  
Old 02-18-2008, 09:10 PM
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 - Forcing the browser not to cache a document

Forcing the browser not to cache a document


If you have a page that seems to be caching via the browser and can't explain why, try adding the following lines of code inside the <head></head> block of your HTML:
Code:
<META HTTP-EQUIV="expires" CONTENT="Fri, 1 Jan 1990 00:00:00 GMT">
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="cache-control" VALUE="no-cache, no-store, must-revalidate">
I've encounted this when I use a form to call another Cold Fusion program that performs file/database updates and then uses CFLOCATION to redirect back to the calling program.

This will solve the cache problem in Netscape, however, Internet Explorer is a different story. If you are using IE 3.xx, the only way to get out of the caching problem is to either upgrade to IE4 or to get rid of the frames. See KB article Q176797 for more information. If you are using IE4, you actually have to add a 2nd <head></head> block at the end of your html code, after the </body> tag but before the </html> tag. In this case, you only need to duplicate the Pragma=no-cache tag.

Code:
 <HTML>
    <HEAD>

        <META HTTP-EQUIV="REFRESH" CONTENT="5">
        <TITLE> Pragma No-cache </TITLE>

    </HEAD>
    <BODY>

        This is an example of where to place the second header section<br>
        so that the "Pragama, No-Cache" metatag will work as it is supposed to.<br>

    </BODY>
    <HEAD>

        <META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">

    </HEAD>
    </HTML>
__________________
Prasanna Vignesh
MCPD | Web Developer
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #23 (permalink)  
Old 02-18-2008, 09:11 PM
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 - Grabbing informaion from another website

Grabbing informaion from another website


If you want to grab a bit of information from another website, you can use the CFHTTP tag to pull in the HTML of the site in question and store it in a variable.

I did basically the same thing in creating a Comic's page that lists all of my favorite comics. It has to scan a few of the comic websites each day since they use a seemingly random number as part of the GIF file names that changes from day to day. Attached is an excerpt of my code that I use to search the html for the GIF file name.

Basically, you need to know of a string of text that will never change (you hope) in it's position to whatever information you want. Search for the location of this string of text and if you find it, search after it for the last of the text you want.

Feel free to steal it. : P Note that it's been a couple months since I used this program so maybe it'll still find the Dilbert strip, maybe it won't.



Example HTML/CFML code:
Code:
<!--- Main program --->

<CFSET title="Dilbert">
<CFSET base="http://www.dilbert.com">
<CFSET url="http://www.dilbert.com/comics/dilbert/">
<CFSET search="/comics/dilbert/archive/images/dilbert">
<CFINCLUDE TEMPLATE="ComicSearch.cfm">
<CFINCLUDE TEMPLATE="HTML.cfm">

<!--- ComicSearch.cfm --->
<CFSET ck=0>

<CFHTTP URL="#url#"
        METHOD="GET">
</CFHTTP>
<CFSET dat=CFHTTP.FileContent>

<CFSET loc1=Find(search,dat)>
<CFIF loc1 EQUAL 0>
  <CFSET ck=1>
<CFELSE>
  <CFSET loc2=Find(Chr(34),dat,loc1)>
  <CFSET strip="#base##Mid(dat,loc1,loc2 - loc1)#">
</CFIF>

<!--- HTML.cfm --->
<CFOUTPUT>
<table border="0" width="90%"><tr><td BGCOLOR="##FFFF00">
<font face="Arial" size="5">&nbsp;&nbsp;#title#</font>
</td></tr></table>
</CFOUTPUT>

<CFIF ck EQUAL 0>
  <CFOUTPUT>
  <a href="#url#"><img src="#strip#" border="0"></a><br><br>
  </CFOUTPUT>
<CFELSE>
  <CFOUTPUT>Unable to determine the image filename<br><br></CFOUTPUT>
  <CFSET ck=0>
</CFIF>
__________________
Prasanna Vignesh
MCPD | Web Developer
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #24 (permalink)  
Old 02-18-2008, 09:12 PM
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 - IE: Changing the contents of your website on the fly with

IE: Changing the contents of your website on the fly with <DIV>


Say you want to change what is displayed on your page based on a user action or you want to change something on the fly for a long-executing process. An example would be the Microsoft Windows Update website with Win2k/XP - it's displaying it's progress as it searches for updates.

With IE, you can use a combination of Javascript and the <DIV> tag to do so.

Note that changing the page contents while the task is still being executed requires the use of the <CFFLUSH> tag - which makes that tag unavailable for CF 4.x and below. Due note that you can still use Javascript functions to update the contents of <div> tags but that limits you to only what can be done after the page generation is complete and the rendered HTML sent to the user.

For an example, let's say that you want to display to the user the percentage complete of the current task - as it's still being executed.

First, we need to "prime the pump" by displaying a div tag that we'll alter later. Note that you must have some text inside the div tag or you will not be able to update it (a Javascript error is generated).

Code:
<CFOUTPUT>
<div id="Audit">The current task is 0% complete.</div>
</CFOUTPUT>
Now updating the contents of that div tag is a breeze.
Code:
<script language="Javascript">
Audit.innerHTML='The current task is #Per#% complete.';
</script>
One thing to keep in mind is that the Javascript block is only executed after it receives the </script> tag.

Here's a Copy-n-Paste demo version. Note that I pad the output buffer with a lot of extra "x" characters inside an HTML comment block on line 2. This is because the CFFLUSH tag will not flush anything unless it has at least 1k of data to send. After the initial flush, you can flush the buffer any time you wish.

Code:
<CFOUTPUT>
<!-- #RepeatString("x",1024)# -->
<font face="Arial" size="4">
<div id="Audit">The current task is 0% complete.</div>
</font>
</CFOUTPUT>
<CFFLUSH>

<CFLOOP index="Per" from="1" to="100">
  <CFOUTPUT>
  <script language="Javascript"> 
  Audit.innerHTML='The current task is #Per#% complete.';
  </script>
  </CFOUTPUT>
  <CFFLUSH>
  <!--- Insert a little delay --->
  <CFLOOP index="loop" from="1" to="10000">
  </CFLOOP>
</CFLOOP>
Another method you could use is to update the value of a <div> block using Javascript timeouts.

Okay, let's say you want to change the text of a block if the user moves the mouse over it and restore it when they move the mouse off.

Code:
<font face="Arial" size="4">
<div onMouseOver="this.innerHTML='Hey, get <b>OFF</b> of me!'"
     onMouseOut="this.innerHTML='I feel so lonely.'">I need a hug.</div>
</font>
The above example shows the use of two Javascript events in order to change the contents of a <div> block - and also shows that you need to stay away from embedding HTML in the middle of your text. If you try the above example, you'll notice that it'll execute the onMouseOut event if you move your mouse cursor to the left or right of "OFF" where the bold tags reside and it won't execute the onMouseOver event until you move your mouse off of the text and then back on.

An important note - when changing the contents of a <div> tag, you are using Javascript - so be sure to escape your special characters with the backslash. Example, you can't display a backslash by just sending a backslash - you have to send TWO backslashes - the first one escapes the 2nd.

Quote:
Bad: Audit.innerHTML='Path C:\Windows\System32';
Good: Audit.innerHTML='Path C:\\Windows\\System32';
__________________
Prasanna Vignesh
MCPD | Web Developer
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #25 (permalink)  
Old 02-18-2008, 09:13 PM
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 - Inserting a LONG field into Oracle

Inserting a LONG field into Oracle


The LONG datatype is a weird one. If you attempt to insert a value that is less than 2000 characters it will return an error. However, if you attempt to insert a value that is greater than 2000 characters, you have to define it as a LONG type before putting it into the database. In the following example the Rules_HTML field is a LONG datatype but it may not be 2000 characters. Here is my CF code to deal with this information:


Example HTML/CFML code:
Code:
<!--- First set a variable to the length of the value of the Rules_HTML field --->
<CFSET RulesHTMLLength = Len(form.Rules_HTML)>

<CFQUERY NAME="UpdatePromo" DATASOURCE="#Application.Datasource#">
<!--- If the Rules_HTML length is gt 2000 characters define it as a LONG field --->
<CFIF RulesHTMLLength GT 2000>
  DECLARE Rules_HTML_Temp LONG;
  BEGIN
  Rules_HTML_Temp := '#Rules_HTML#';
</CFIF>

UPDATE PROMO
SET   Banner_Image_ID = #form.Banner_Image_ID#
  , Logo_Image_ID = #form.Logo_Image_ID#
  , Front_Page_Image_ID = #form.Front_Page_Image_ID#
  , Begin_Date = '#DateFormat(form.Begin_Date, "DD-MMM-YYYY")#'
  , End_Date = '#DateFormat(form.End_Date, "DD-MMM-YYYY")#'
  , Notes = '#form.Notes#'
  , Summary_HTML = '#form.Summary_HTML#'
  , Tag_Line = '#form.Tag_Line#'
<!--- If the Rules_HTML field is a long datatype, insert the variable pointing to the value --->
<CFIF RulesHTMLLength GT 2000>
  , Rules_HTML = Rules_HTML_Temp
<CFELSE>
<!--- If it's not a long datatype, do a normal insert, with the actual rules_html field itself --->
  , Rules_HTML = '#form.Rules_HTML#'
</CFIF>
WHERE Promo_ID = #form.Promo_ID#
<!--- Then if the rules_html field is a long field, you have to add a semicolon and an END statement --->
<CFIF RulesHTMLLength GT 2000>
;
END;
</CFIF>
</CFQUERY>
__________________
Prasanna Vignesh
MCPD | Web Developer
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #26 (permalink)  
Old 02-18-2008, 09:13 PM
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
Default ColdFusion Tips & Tricks - Issues with comma separated documents and Excel

Issues with comma separated documents and Excel


This is just a FYI in case you ever run into this problem.

If you are dynamically creating a delimited text file to use for importing into Excel, you might want to take note of this in order to prevent catching flack from the overzealous users of your projects.

First, forget about the CSV extension. Don't use it. The document may open up correctly if downloaded and opened from a URL but if the users save it to their desktop and then open it, Excel seems to ignore the cell delimiter and stuffs everything into column A.

Also, Netscape likes to consider CSV files as text and displays it in the browser instead of opening Excel.

In order to resolve the above issues and others, perform the following steps.

* Use the XLS file extension. Excel, upon opening the document, will realize it's a text file and will translate it.
* Use the TAB - Chr(9) - as the cell delimiter.
* Write the file to the server's hard drive.
* Use <CFCONTENT> to send the file to the user.

In your URL for downloading the document to the user, simply call your template again with a URL variable specifying the file to send the user and the following code will send it to the user without altering whatever information is currently being displayed on the web site. Assuming your template name is "GenerateReport.cfm", your HTML would read: <a href="GenerateReport.cfm?SendFile=#filename#">

The two Find functions ensure the user isn't trying to get the program to download something they are not supposed to be downloading.

Example HTML/CFML code:

<!--- See if we need to download the user's report to them --->
<CFPARAM name="URL.SendFile" DEFAULT="">
<CFIF URL.SendFile NEQ "" AND Find("/",URL.SendFile) EQ 0 AND Find("\",URL.SendFile) EQ 0>
<cfcontent type="application/vnd.ms-excel" file="#GenFilePath##URL.SendFile#" deletefile="No">
<CFABORT>
</CFIF>
__________________
Prasanna Vignesh
MCPD | Web Developer
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #27 (permalink)  
Old 02-18-2008, 09:15 PM
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 for illegal characters

javascript: Checking for illegal characters


These functions checks for illegal characters in a form field. The ValidString( ) function does all the work but the others listed below are generic shortcuts for typical functions. They return true or false, you'll have to code in your own alert message in your validation function if these return false.

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

// Returns true if the string only contains alpha characters (empty string = true)
function isAlpha(txt)
{
	return ValidString(txt,'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz');
}

// Returns true if the string only contains numeric characters (empty string = true)
function isNumeric(txt)
{
	return ValidString(txt,'0123456789');
}

// Returns true if the string only contains alpha numeric characters (empty string = true)
function isAlphaNumeric(txt)
{
	return ValidString(txt,'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789');
}

// Returns true if the CheckString only contains characters passed in ValidString (empty string = true)
function ValidString(ChkString,ValidString)
{
	for (i=0; i<ChkString.length; i++)
	{
		if (ValidString.indexOf(ChkString.substring(i,i+1)) == -1) return false;
	}
	return true;
}


function SubmitForm()
{
	if (!isAlpha(document.Test.Alpha.value)) { alert('Alpha Only must only contain A-Z or a-z');return }
	if (!isAlphaNumeric(document.Test.AlphaNumeric.value)) { alert('Alpha Numeric must only contain A-Z, a-z, or 0-9'); return }
	if (!isNumeric(document.Test.Numeric.value)) { alert('Number must only contain 0-9'); return }
	alert('All is okay!');
}
</script>

<form name="Test">
Alpha Only: <input type="Text" name="Alpha" value=""><br>
Alpha Numeric Only: <input type="Text" name="AlphaNumeric" value=""><br>
Numeric Only: <input type="Text" name="Numeric" value=""><br>
<input type="Button" value="Go!" onClick="SubmitForm()">
</form>
__________________
Prasanna Vignesh
MCPD | Web Developer
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #28 (permalink)  
Old 02-21-2008, 12:22 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 if required fields have data

javascript: Checking if required fields have data

Instead of creating multiple Javascript if conditions for every required form field that you have, you can call one function and it will check all of the fields you specified and display an error message if any do not have values.

The function uses a trim( ) function to strip out leading and trailing spaces.


Example HTML/CFML code:
Code:
<script language="Javascript">
function trim(thisString){
	var newString = thisString;
	while (newString.charCodeAt(0) < 33)
	{
		newString = newString.substring(1,newString.length);
	}
	
	while (newString.charCodeAt(newString.length - 1) < 33)
	{
		newString = newString.substring(0, newString.length - 1);
	}
	return newString;
}

// Validate that a list of fields contain a value (leading and traling spaces are removed)
// First paramter: the form reference.  If your form name is "ServiceForm", then pass "document.ServiceForm"
// Second Parameter: A pipe delimited list of field names (case senastive)
// Third Parameter: A pipe delimited list of field descriptions
//
function ValidateRequiredFields(thisform,Fields,Desc)
{
	var tmpVal='';
	var FieldArray=new Array();
	var DescArray=new Array();
	var tmp=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: ValidateRequiredFields - Passed lists do not have the same length');
		return false;
	}
	// Validate fields
	for (i=0; i < DescArray.length; i++)
	{
		eval('tmpVal=thisform.' + FieldArray[i] + '.value');
		if (trim(tmpVal) == '')
		{
			alert(DescArray[i] + ' is required.');
			eval('thisform.' + FieldArray[i] + '.focus()');
			return false;
		}
	}
	return true;
}

function SubmitForm()
{
	if (!ValidateRequiredFields(document.Test,'FirstName|LastName','First Name|Last Name')) return false;
	alert('All is okay!');
}
</script>

<form name="Test">
First Name: <input type="Text" name="FirstName" value=""><br>
Last Name: <input type="Text" name="LastName" value=""><br>
<input type="Button" value="Go!" onClick="SubmitForm()">
</form>
__________________
Prasanna Vignesh
MCPD | Web Developer
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #29 (permalink)  
Old 02-21-2008, 12: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
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #30 (permalink)  
Old 02-21-2008, 12:25 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 multi-dropdown selection b

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

This function comes in handy if you have multiple required multi-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 (will return false if none are)
// Example: if (!ValidateMultipleDropDown(document.ServiceForm,'ChannelCodeDesc|UserLevel','Channel Code|User Level')) return false;
function ValidateMultipleDropDown(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: ValidateMultipleDropDown - Passed lists do not have the same length');
		return false;
	}
	// Validate fields
	for (i=0; i<FieldArray.length;i++)
	{
		tmp=0;
		eval('L=thisform.' + FieldArray[i] + '.length');
		for (x=0; x<L; x++)
		{
			eval('idx=thisform.' + FieldArray[i] + '.options[' + x + '].selected');
			if (idx == true) tmp++;
		}
		if (tmp == 0)
		{
			alert('Please select an item for ' + DescArray[i] + '.');
			return false;
		}
	}
	return true;
}

function SubmitForm()
{
	if (!ValidateMultipleDropDown(document.Test,'CellFeatures','Cell Features')) return false;

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

<form name="Test">
Select the cell phone features you want:<br>
<select name="CellFeatures" size="7">
	<option>Automatic Pizza finder</option>
	<option>Belt clip with built-in yellow sticky pad, PostIt</option>
	<option>Headset with an super long cord</option>
	<option>Mother-in-law mute button</option>
	<option>Mother-in-law call blocking</option>
	<option>Three dozen face plates for every mood</option>
	<option>Wireless Web</option>
</select>
<br><br>
<input type="Button" value="Go!" onClick="SubmitForm()">
</form>
__________________
Prasanna Vignesh
MCPD | Web Developer
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #31 (permalink)  
Old 02-21-2008, 12:26 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: Moving items from one multi-select box to ano

javascript: Moving items from one multi-select box to another


Seems like everybody tends to shy away from this in websites - moving an item from one multi-select box to another. I had to perform the same task so I thought I'd share the Javascript routines that made it easy.

What you need is two select boxes (of course) and two normal buttons to kick off a javascript routine. Both buttons call the same routine but specify the select boxes in reverse order.

Syntax: SelectMoveRows(<source select box>,<destination select box>);
Example: SelectMoveRows(document.Example.Features,document. Example.FeatureCodes);

The way it works is that it will scan through the values of the source select box and if any rows that are selected, it will add it to the bottom of the destination select box and then remove it from the source select box. Once it has scanned through the source select box, it will call a second function called "SelectSort" in order to sort the values of the destination select box using a simple bubble sort. Note that the sort is a ASCII sort so if you have three rows with the values of "Row 1", "Row 2", and "Row 10", "Row 10" will be sorted between "Row 1" and "Row 2".

If you look at the example HTML attached below, both the Add and Remove buttons call the same Javascript function, however, the source and destination fields are reversed for the Remove button. (Make sure they're buttons, not submit buttons!)

This Javascript routine works for Internet Explorer 5+, Netscape 4.7, and Netscape 7.0

Example HTML/CFML code:


Code:
<html>
<head>
<title>Multi-list copy example</title>
<body>
<script language="Javascript">
function SelectMoveRows(SS1,SS2)
{
    var SelID='';
    var SelText='';
    // Move rows from SS1 to SS2 from bottom to top
    for (i=SS1.options.length - 1; i>=0; i--)
    {
        if (SS1.options[i].selected == true)
        {
            SelID=SS1.options[i].value;
            SelText=SS1.options[i].text;
            var newRow = new Option(SelText,SelID);
            SS2.options[SS2.length]=newRow;
            SS1.options[i]=null;
        }
    }
    SelectSort(SS2);
}
function SelectSort(SelList)
{
    var ID='';
    var Text='';
    for (x=0; x < SelList.length - 1; x++)
    {
        for (y=x + 1; y < SelList.length; y++)
        {
            if (SelList[x].text > SelList[y].text)
            {
                // Swap rows
                ID=SelList[x].value;
                Text=SelList[x].text;
                SelList[x].value=SelList[y].value;
                SelList[x].text=SelList[y].text;
                SelList[y].value=ID;
                SelList[y].text=Text;
            }
        }
    }
}
</script>
<form name="Example">
<table border="0" cellpadding="3" cellspacing="0">
    <tr>
        <td>
            <select name="Features" size="9" MULTIPLE>
                <option value="2">Row 2</option>
                <option value="4">Row 4</option>
                <option value="5">Row 5</option>
                <option value="6">Row 6</option>
                <option value="7">Row 7</option>
                <option value="8">Row 8</option>
                <option value="9">Row 9</option>
            </select>
        </td>
        <td align="center" valign="middle">
            <input type="Button" value="Add >>" style="width:100px" onClick="SelectMoveRows(document.Example.Features,document.Example.FeatureCodes)"><br>
            <br>
            <input type="Button" value="<< Remove" style="width:100px" onClick="SelectMoveRows(document.Example.FeatureCodes,document.Example.Features)">
        </td>
        <td>
            <select name="FeatureCodes" size="9" MULTIPLE>
                <option value="1">Row 1</option>
                <option value="3">Row 3</option>
            </select>
        </td>
    </tr>
</table>
</form>

</body>
</html>
__________________
Prasanna Vignesh
MCPD | Web Developer
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #32 (permalink)  
Old 02-21-2008, 12:28 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: Smart Select Lists

javascript: Smart Select Lists


The nice thing about select lists is that if you click on the list and then hit a key, the list will jump down to the letter you selected. So if you have a list with a thousand entries, you can hit "M" to jump to the first entry that starts with "M" (case insensitive). The problem with this is that if you have a hundred entries that start with "M", you still have to scroll down and search for the value you want.

To provide a method of allowing the user to type in a value and have the select list auto-select the first matching value, you need to provide a text field above the select box. Note that the Javascript below will only work with single-select lists, not multiple-select lists.

The first example below will loop over the entire list to search for a matching string and is ideal for short lists for simplicity.

The second example below is for lists that contain hundreds or even thousands of values. It creates an array, one position for each letter of the alphabet, that stores the location of it's first occurrence. It'll also exit the search if it's searching for strings that start with a specified letter and it comes to a list option that starts with a letter that comes later in the alphabet. For example, if the user types "Eb" and there is no list entry that starts with "Eb", it'll stop searching when it hits a list entry that starts with "F".

Both of the examples will perform a case insensitive match.

Note: For best results, all selection lists should be sorted alphabetically.

Example HTML/CFML code:


Example 1, for short select lists
Code:
<script language="Javascript">
function SchKey(obj)
{
  // event.keyCode holds the ASCII value of the key pressed
  var k=event.keyCode;
  // Only execute if user presses letter, number, or space
  if ((k>=65 && k<=90) || (k>=95 && k<=122) || (k>=48 && k<=57) || k==32)
  {
    var SL=document.MyForm.SelectList;
	var SearchStr=document.MyForm.SearchKey.value;
    for (i=0; i<SL.options.length; i++)
    {
      if (SL.options[i].text.toUpperCase().substr(0,SearchStr.length)==SearchStr.toUpperCase())
      {
        // We have  a match - highlight it and set the index so the loop will end
        SL.selectedIndex=i;
        i=SL.length + 1;
      }
    }
  }
  return true;
}
</script>
<form name="MyForm">
<input type="Text" name="SearchKey" onKeyUp="return SchKey()"><br>
<select name="SelectList" size="12">
  <option>a</option><option>b</option><option>ba</option>
  <option>c</option><option>d</option><option>da</option>
  <option>e</option><option>f</option><option>fa</option>
  <option>g</option><option>h</option><option>ha</option>
  </select>
</form>

================================================== ===================

Example 2, for very long select lists
Code:
<script language="Javascript">
var StrInit=0;
var StrIdx=new Array(0);
StrIdx[0]=0;
for (i=1; i<=25; i++){StrIdx[i]=-1;}

function SchKey(obj)
{
  // event.keyCode holds the ASCII value of the key pressed
  var k=event.keyCode;
  // Only execute if user presses letter, number, or space
  if ((k>=65 && k<=90) || (k>=95 && k<=122) || (k>=48 && k<=57) || k==32)
  {
    if (StrInit == 0) InitStrArray();
    var SL=document.MyForm.SelectList;
    var SearchStr=document.MyForm.SearchKey.value;
    var SearchKey=SearchStr.toUpperCase().charAt(0);
    var StartAt=StrIdx[SearchStr.toUpperCase().charCodeAt(0) - 65];
    for (i=StartAt; i<SL.options.length; i++)
    {
      if (SL.options[i].text.toUpperCase().substr(0,SearchStr.length)==SearchStr.toUpperCase())
      {
        // We have  a match - highlight it and set the index so the loop will end
        SL.selectedIndex=i;
        i=SL.length + 1;
      }
      if (i < SL.length && SL.options[i].text.toUpperCase().charAt(0) != SearchKey)
      {
        // We've passed the letter we're looking for, means not found, exit loop
        i=SL.length + 1;
      }
    }
  }
  return true;
}
function InitStrArray()
{
  var SL=document.MyForm.SelectList;
  var c=0;
  for (i=0; i<SL.options.length; i++)
  {
    c=SL.options[i].text.toUpperCase().charCodeAt(0);
    if (c >= 65 && c <= 90)
    {
      c=c - 65;
      if (StrIdx[c] == -1) StrIdx[c]=i;
    }
  }
  // Copy any undefined entries to match the preceding entry
  for (i=1; i<=25; i++)
  {
    if (StrIdx[i] == -1) StrIdx[i]=StrIdx[i - 1];
  }
  // Set the flag indicating we've built the index
  StrInit=1;
  return;
}
</script>
<form name="MyForm">
<input type="Text" name="SearchKey" onKeyUp="return SchKey()"><br>
<select name="SelectList" size="12">
  <option>b</option><option>d</option><option>f</option>
  <option>h</option><option>hn</option><option>hd</option>
  </select>
</form>
__________________
Prasanna Vignesh
MCPD | Web Developer
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #33 (permalink)  
Old 02-21-2008, 12:29 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: Trimming form fields

javascript: Trimming form fields



This function simulates the CF Trim( ) function.


Example HTML/CFML code:
Code:
function trim(thisString){
	var newString = thisString;
	while (newString.charCodeAt(0) < 33)
	{
		newString = newString.substring(1,newString.length);
	}
	
	while (newString.charCodeAt(newString.length - 1) < 33)
	{
		newString = newString.substring(0, newString.length - 1);
	}
	return newString;
}
__________________
Prasanna Vignesh
MCPD | Web Developer
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #34 (permalink)  
Old 02-21-2008, 12:30 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
Smile ColdFusion Tips & Tricks - Javascript: Validating Integer and Float fields

javascript: Validating Integer and Float fields


Here's a set of Javascript functions that will allow you to check to see if text elements on your form contain valid numeric values. Optionally, you can allow the value to contain commas or be a negative number. You can validate all of your integer fields with one Javascript function call.

ValidateIntegerFields(thisform,Fields,Desc,AllowCo mma,AllowNeg)
ValidateFloatFields(thisform,Fields,Desc,AllowComm a)

thisform is the form reference, Fields will contain a pipe delimited list of field names (case sensative), Desc is also a pipe delimited list of field descriptions, AllowComma - true or false, AllowNeg - true or false. If you specify AllowComma = true, all it does is to simply allow the comma, it does not validate the correct placement of the comma. Recomend that you strip out all commas in your form action page.

If the user does not specify a value at all, the function will return true (okay). Use the ValidateRequiredFields( ) function to check to see if form elements actually has a value.

Example HTML/CFML code:
Code:
<script language="Javascript">
function trim(thisString){
	var newString = thisString;
	while (newString.charCodeAt(0) < 33)
	{
		newString = newString.substring(1,newString.length);
	}
	
	while (newString.charCodeAt(newString.length - 1) < 33)
	{
		newString = newString.substring(0, newString.length - 1);
	}
	return newString;
}

function ValidateIntegerFields(thisform,Fields,Desc,AllowComma,AllowNeg)
{
	var tmpVal='';
	var FieldArray=new Array();
	var DescArray=new Array();
	var tmp=0;
	var tmpMsg='';
	// 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: ValidateInteger - Passed lists do not have the same length');
		return false;
	}
	// Validate fields
	for (i=0; i<FieldArray.length;i++)
	{
		tmpMsg='';
		eval('tmpVal=thisform.' + FieldArray[i] + '.value');
		if (!AllowNeg && tmpVal < 0)
		{
			alert(DescArray[i] + ' may not be a negative value.');
			// Fix for IWOF NSO
			if (FieldArray[i].substring(0,4) == 'Hold')
			{
				eval('thisform.Qty_' + FieldArray[i].substring(5) + '.select()');
			} else {
				eval('thisform.' + FieldArray[i] + '.select()')
			}
			return false;
		}
		if (!ValInt(tmpVal,AllowComma))
		{
			if (AllowComma != 1 && tmpVal.indexOf(',') != -1) tmpMsg=' without commas';
			if (tmpVal.indexOf('.') != -1) tmpMsg=' (no decimal fraction)';
			alert(DescArray[i] + ' must be an integer value' + tmpMsg + '.');
			// Fix for IWOF NSO
			if (FieldArray[i].substring(0,4) == 'Hold')
			{
				eval('thisform.Qty_' + FieldArray[i].substring(5) + '.select()');
			} else {
				eval('thisform.' + FieldArray[i] + '.select()')
			}
			return false;
		}
	}
	return true;
}




function ValidateFloatFields(thisform,Fields,Desc,AllowComma)
{
	var tmpVal='';
	var FieldArray=new Array();
	var DescArray=new Array();
	var tmp=0;
	var tmpMsg='';
	// 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: ValidateFloat - Passed lists do not have the same length');
		return false;
	}
	// Validate fields
	for (i=0; i<FieldArray.length;i++)
	{
		tmpMsg='';
		eval('tmpVal=thisform.' + FieldArray[i] + '.value');
		if (!ValFloat(tmpVal,AllowComma))
		{
			if (AllowComma != 1 && tmpVal.indexOf(',') != -1) tmpMsg=' without commas';
			alert(DescArray[i] + ' must be a numeric value' + tmpMsg + '.');
			eval('thisform.' + FieldArray[i] + '.focus()')
			return false;
		}
	}
	return true;
}





function ValInt(ObjectValue,AllowComma)
{
	// Used internally by VaidateInteger

	//Returns true if value is a number or is NULL
	//otherwise returns false	
	
	if (ObjectValue.length == 0) return true;
	
	//Returns true if value is an integer defined as
	//   having an optional leading + or -.
	//   otherwise containing only the characters 0-9.
	var decimal_format = ".";
	var check_char;
	
	//The first character can be + -  blank or a digit.
	check_char = ObjectValue.indexOf(decimal_format)
	//Was it a decimal?
	if (check_char < 1) return ValFloat(ObjectValue,AllowComma); else return false;
}

function ValFloat(ObjectValue,AllowComma)
{
	// Used Internally by ValidateInt, ValidateFloat

	//Returns true if value is a number or is NULL
	//otherwise returns false	
	
	if (ObjectValue.length == 0) return true;
	
	//Returns true if value is a number defined as
	//   having an optional leading + or -.
	//   having at most 1 decimal point.
	//   otherwise containing only the characters 0-9.
	var start_format = " .+-0123456789";
	var number_format = " .0123456789";
	if (AllowComma == 1) number_format=number_format + ',';
	var check_char;
	var decimal = false;
	var trailing_blank = false;
	var digits = false;
	
	//The first character can be + - .  blank or a digit.
	check_char = start_format.indexOf(ObjectValue.charAt(0))
	//Was it a decimal?
	if (check_char == 1)
		decimal = true;
	else if (check_char < 1)
		return false;
	
	//Remaining characters can be only . or a digit, but only one decimal.
	for (var i = 1; i < ObjectValue.length; i++)
	{
		check_char = number_format.indexOf(ObjectValue.charAt(i))
		if (check_char < 0)
			return false;
		else if (check_char == 1)
		{
			if (decimal)		// Second decimal.
				return false;
			else
				decimal = true;
		}
		else if (check_char == 0)
		{
			if (decimal || digits) trailing_blank = true;
			// ignore leading blanks
		}
		else if (trailing_blank)
			return false;
		else
			digits = true;
	}	
	//All tests passed, so...
	return true
}
function SubmitForm()
{
	if (!ValidateIntegerFields(document.Test,'Integer','Integer Field',false,false)) return false;
	if (!ValidateIntegerFields(document.Test,'IntegerNeg','Integer Field with negative values allowed',false,true)) return false;
	if (!ValidateIntegerFields(document.Test,'IntegerComma','Integer Field with commas allowed',true,false)) return false;

	if (!ValidateFloatFields(document.Test,'Float','Float Field',false,false)) return false;
	if (!ValidateFloatFields(document.Test,'Flo